microsoft / microsoft/TypeScript

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

Offen
#36,535 0 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

Needs Investigation
Vorherrschende Sprache
Go
Sterne
111k
Forks
14.3k
Ø Merge
2 T. 4 Std.
Gemergte PRs (30 T.)
132

Beschreibung

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:

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Rechercherichtung

Beginne mit der TypeScript Playground-Reproduktion und vergleiche die drei Aufrufe in callMethod, insbesondere die Fälle 1 und 2 mit dem funktionierenden Fall 3. Das Issue ist abgeschlossen, wenn der Compiler Fall 2 und möglicherweise Fall 1 akzeptiert und dabei die erwartete Parameterbeziehung für die indizierte Methode beibehält.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
typescript
Bereich
compilers
Issue-Typ
Bug
Schwierigkeit
4/5
Geschätzter Aufwand
3-5 Tage
Aktivitätsstatus
Veraltet
Klarheit
Größtenteils klar
Anfängerfreundlichkeit
38/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.