microsoft / microsoft/TypeScript
Type narrowing with assertions containing truthy literals
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: 4.2.0-dev.20201109
Search Terms:
type narrowing truthy
type narrowing assertion
conditional throw
Code
function test(foo?: number) {
if (!foo) throw new Error();
return foo.toFixed();
}
function testWithLiteralTrue(foo?: number) {
if (!foo && true) throw new Error();
return foo.toFixed();
}
function testWithTruthyLiteral(foo?: number) {
if (!foo && "str") throw new Error();
return foo.toFixed(); // Object is possibly 'undefined'.
}
Expected behavior:
In all three functions typescript would know foo is a number after the assertion.
Actual behavior:
In the last example, testWithTruthyLiteral, typescript complains foo may be undefined. This is the same behavior for all known truthy values except for literal true.
Related Issues:
https://github.com/microsoft/TypeScript/issues/29323
It sounds like from https://github.com/microsoft/TypeScript/issues/29323#issuecomment-454548280 that determining truthiness of expressions could lead to circular dependencies between compiler passes, but that literal true has been special cased. This should be able to be extended to truthy literals without the circular dependency concern.
And for context, like others that have brought up similar issues, this stems from wanting a truthy token that can be used for a minification hook without affecting the types or code execution.
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 l’esempio TypeScript Playground collegato e confronta le tre funzioni usando il literal true e altri literal truthy. Leggi l’issue correlata #29323 e la discussione collegata sull’analisi della truthiness e sulle dipendenze tra i pass del compilatore. Il lavoro è completato quando i literal truthy restringono foo in modo coerente dopo il throw condizionale, con copertura per i casi segnalati.
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
- Specificata chiaramente
- Idoneità per principianti
- 45/100