microsoft / microsoft/TypeScript

Parameter types not being inferred in a class method whose type is indexed from an interface

Open
#36,535 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Needs Investigation
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:

Playground

Related Issues:

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.