microsoft / microsoft/TypeScript
implicit 'any' in method with parameter of inferred generic type
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 1d 19h
- Merged PRs (30d)
- 117
Description
🔎 Search Terms
implicit 'any' method parameter inferred generic type
🕗 Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about type inference
⏯ Playground Link
💻 Code
type Constructor<T> = {
new (...args: never[]): T;
};
interface GenericParams<T> {
bar: (t: T) => void;
}
type List<T extends readonly {}[]> = {
[K in keyof T]: [Constructor<T[K]>, GenericParams<T[K]>];
};
declare function foo<T extends readonly {}[]>(params: List<[...T]>): void;
class Foo {
test() {}
}
class Bar {}
// Inference fails
foo([
//^?
[Foo, {bar(t) {
}}],
[Bar, {bar(t) {
}}]
])
// Inference works
foo([
[Foo, {bar(t) {
t.test();
}}]
])
interface NumberParams<T> {
bar: (t: number) => void;
}
type List2<T extends readonly {}[]> = {
[K in keyof T]: [Constructor<T[K]>, NumberParams<T[K]>];
};
declare function foo2<T extends readonly {}[]>(params: List2<[...T]>): void;
// Inference works
foo2([
// ^?
[Foo, {bar(t) {
}}],
[Bar, {bar(t) {
}}]
])
🙁 Actual behavior
In the foo example, the parameter t in the associated bar methods are inferred as type any. It seems that TypeScript should be able to infer the actual types of the parameters.
🙂 Expected behavior
t is inferred as type T in each case, i.e. t should be Foo in the Foo case, and Bar in the Bar case.
There are two additional cases provided here: one with a single element in the provided array, and one where the parameters are not generic (number). In both cases, type inference does assign the correct non-any type. It's unclear what exactly the issue is in the first case.
Additional information about the issue
It's possible this is related to #47599, though I don't have enough knowledge of the internals to say whether or not it's the same class of bug. I haven't found another issue reporting this same behaviour.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the linked TypeScript Playground reproduction and compare the generic foo calls with the single-element and non-generic foo2 cases. Trace the type inference behavior around the mapped List type; done means each bar parameter is inferred as Foo or Bar rather than any, while the other cases remain correct.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 38/100