microsoft / microsoft/TypeScript
Parameter types not being inferred in a class method whose type is indexed from an interface
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
TypeScript Version: 3.7.4
Search Terms:
Index type
Parameter type of method
Inferring parameter types
Code
interface Parameters1 {
paramA: number;
paramB: string;
}
interface Parameters2 {
paramC: boolean;
}
interface SomeFunctions {
foo(options: Parameters1): void;
bar(options: Parameters2): void;
}
class AClass implements SomeFunctions {
public foo(options: Parameters1): void { }
public bar(options: Parameters2): void { }
}
const aClassInstance = new AClass();
function callMethod<K extends keyof SomeFunctions>(
methodName: K,
options: Parameters<SomeFunctions[K]>[0]
) {
// 1. Does not work:
// Argument of type 'Parameters<SomeFunctions[K]>[0]' is not assignable to parameter of type 'Parameters1 & Parameters2'.
aClassInstance[methodName](options);
// 2. Also does not work
// Argument of type 'Parameters<SomeFunctions[K]>[0]' is not assignable to parameter of type 'Parameters1 & Parameters2'.
// Type 'Parameters<SomeFunctions[K]>[0]' is not assignable to type 'Parameters1'.
(aClassInstance[methodName] as SomeFunctions[K])(options);
// 3. Does work, even though it is essentially the same thing as 2
type MethodType = (o: typeof options) => ReturnType<SomeFunctions[K]>
(aClassInstance[methodName] as MethodType)(options);
}
Expected behavior:
Case 2 should work. Possibly also case 1.
Typescript should know that options is the correct type
Actual behavior:
Only case 3 works, even though it is more or less the same as case 2
Playground Link:
Related Issues:
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 TypeScript Playground reproduction and compare the three calls in callMethod, especially cases 1 and 2 versus the working case 3. The issue is done when the compiler accepts case 2, and possibly case 1, while preserving the expected parameter relationship for the indexed method.
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
- Mostly clear
- Newbie friendliness
- 38/100