microsoft / microsoft/TypeScript
Parameter types not being inferred in a class method whose type is indexed from an interface
Nessuno ha ancora preso questa issue.
- Lingua principale
- Go
- Stelle
- 111k
- Fork
- 14.3k
- Merge medio
- 2g 4h
- PR unite (30g)
- 132
Descrizione
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:
Guida per i contributori
Apri la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Direzione di ricerca
Inizia con la riproduzione in TypeScript Playground e confronta le tre chiamate in callMethod, soprattutto i casi 1 e 2 rispetto al caso 3 funzionante. L’issue è completata quando il compilatore accetta il caso 2, ed eventualmente il caso 1, preservando la relazione prevista tra i parametri del metodo indicizzato.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- typescript
- Ambito
- compilers
- Tipo di issue
- Bug
- Difficoltà
- 4/5
- Tempo stimato
- 3-5 giorni
- Stato di attività
- Ferma
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 38/100