microsoft / microsoft/TypeScript
Inferred type parameter does not satisfy constraint
Nessuno ha ancora preso questa issue.
- Lingua principale
- Go
- Stelle
- 111k
- Fork
- 14.4k
- Merge medio
- 1g 19h
- PR unite (30g)
- 117
Descrizione
Bug Report
🔎 Search Terms
generic constraint, inference, invalid, specified, manually, explicitly, invalid
🕗 Version & Regression Information
- This changed between versions 3.3 and 3.5
⏯ Playground Link
Playground link with relevant code
💻 Code
declare function f<T, U extends T>(cb: (u: U) => T): U
const v = f(u => "x");
// const v: unknown <-- wait, what?
// function f<string, unknown>(cb: (u: unknown) => string): unknown
f<string, unknown>(u => "x"); // error, of course
// -----> ~~~~~~~
// Type 'unknown' does not satisfy the constraint 'string'.
🙁 Actual behavior
In TS3.5+, the type parameter T is inferred to be string, and U is inferred to be unknown in the first call to f(). But then U extends T is not met; you couldn't even manually specify T and U like this when calling f(), as shown in the second call to f().
(In TS3.3, T and U are both inferred as {}.)
🙂 Expected behavior
Either I'd expect both T and U to be string, or I'd expect an error where the compiler says it cannot find a suitable candidate for U. Presumably the compiler has not inferred T before it needs to infer U, and so it constrains U to T's constraint which is implicitly unknown, and then falls back to that. But it never circles back to make sure that such a fallback actually works for U extends T.
I came upon this while looking for an answer to this SO question. This behavior is weird, right? I haven't found an existing issue for it.
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
Riproduci l’esempio collegato di TypeScript Playground e confronta il comportamento segnalato con TypeScript 3.3 e 3.5+. Inizia tracciando l’inferenza dei tipi generici e il controllo dei vincoli per le chiamate di funzione mostrate. Il lavoro è completato quando il compilatore gestisce in modo coerente il vincolo U extends T inferito e sono presenti test di regressione per il comportamento atteso selezionato.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- typescript
- Ambito
- compilers
- Tipo di issue
- Bug
- Difficoltà
- 5/5
- Tempo stimato
- Più di una settimana
- Stato di attività
- Ferma
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 32/100