microsoft / microsoft/TypeScript
Overload causes generic function to loose type specificity
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Go
- Sterne
- 111k
- Forks
- 14.4k
- Ø Merge
- 1 T. 19 Std.
- Gemergte PRs (30 T.)
- 117
Beschreibung
Bug Report
🔎 Search Terms
generic overloaded function type narrowing
🕗 Version & Regression Information
- This is the behavior in every version I tried (4.8, 4.9)
⏯ Playground Link
💻 Code
interface A {
a: 1;
}
interface B extends A {
b: 2;
}
interface Wrapper1<T extends A> {
value: T;
}
interface Wrapper2<T extends A> {
value: T;
}
function unwrap<T extends A>(wrapped: Wrapper1<T>): T
function unwrap<T extends A>(wrapped: Wrapper2<T>): T // Comment out this line, and types will become inferred correctly
function unwrap<T extends A>(wrapped: Wrapper1<T> | Wrapper2<T>): T {
return wrapped.value;
}
const b: B = { a: 1, b: 2 };
const wrapped: Wrapper1<B> = { value: b }
const test1 = unwrap(wrapped); // test1: B (correct)
const test2 = Promise.resolve(wrapped).then(unwrap); // test2: Promise<A> (should be Promise<B>)
const test3 = [wrapped].map(unwrap); // test3: A[] (should be B[])
🙁 Actual behavior
In test2 and test3, the generic type of the overloaded function unwrap looses it's specificity. The types can be narrowed to Promise<B> and B[] respectively, but actually it is inferred as Promise<A> and A[] respectively. Removing the one of the overloads of the function unwrap (so it is no longer overloaded) will resolve the problem.
🙂 Expected behavior
As explained above, the inferred types of test2 and test3 should be inferred as Promise<B> and B[] respectively.
Beitragsleitfaden
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
Beginne mit der verlinkten TypeScript Playground-Reproduktion und vergleiche die Inferenz für test1, test2 und test3, wenn beide Overloads vorhanden sind. Verfolge das Verhalten des generischen Overloads und der Typinferenz; fertig ist es, wenn test2 Promise und test3 B[] ist, ohne einen Overload zu entfernen.
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
- 35/100