microsoft / microsoft/TypeScript
TS 3.7: unlike `x is T`, `asserts x is T` cannot close over generics defined in outer scopes
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.0-dev.20191016
Search Terms:
asserts, asserts return, asserts higher order, asserts type, 2775
Code
function literal<T extends keyof any>(lit: T): {
is(value: any): value is T
assert(value: any): asserts value is T
} {
return null as any; // implementation doesn't matter
}
const isHi = literal("hi")
const x: unknown = "test"
if (isHi.is(x)) {
console.log(x) // x is correctly inferred to be 'hi' :)
}
isHi.assert(x); // error: Assertions require every name in the call target to be declared with an explicit type annotation.(2775)
console.log(x); // x should be inferred to be 'hi' here :(
Expected behavior:
No compile error, x is inferred to be "hi" on the last line.
Actual behavior:
Compile error on isHi.assert. Assertions require every name in the call target to be declared with an explicit type annotation.(2775)
Construction higher order type guards is possible without problem (as shown in the snippet). This mechanism used heavily in libraries like io-ts and mobx-state-tree.
However, when trying to extend the latter library with assertion functionality for more convenient control flow, we run into this issue.
We can build type.is properly, but not type.assert, although they seem to be needing the exact same type / depth of type analysis; if type guards can close over T, so should type assertions?
Playground Link: link
Related Issues:
#34523
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 collegata in TypeScript Playground e analizza l’issue #34523 correlata, confermando diagnostic 2775 per l’esempio di asserzione di ordine superiore. Il lavoro è completato quando l’esempio viene compilato senza quell’errore e l’uso finale di x viene inferito come "hi".
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
- 35/100