microsoft / microsoft/TypeScript
Type narrowing in loose equality fails for edge cases like empty string and zero
Nessuno ha ancora preso questa issue.
- Lingua principale
- Go
- Stelle
- 111k
- Fork
- 14.4k
- Merge medio
- 1g 19h
- PR unite (30g)
- 117
Descrizione
TypeScript Version: 3.8.3
Search Terms:
type narrowing loose equality
type guard loose equality
loose comparison empty string zero
non-strict comparison empty string zero
type guard empty string zero
coercion double equals
type guard coercion fails
Code
TS misses edge cases when narrowing down types in loose equality comparisons.
Following the example from the new handbook on Equality narrowing, if you replace the strict equality with a loose equality, you're rocket is ready to explode. If you pass in the empty string and zero the if condition passes and accessing toUpperCase() on a number fails.
function foo(x: string | number, y: string | boolean) {
if (x == y) {
// We can now call any 'string' method on 'x' or 'y'.
x.toUpperCase();
y.toLowerCase();
}
else {
console.log(x);
console.log(y);
}
}
foo(0, "");
It might be worth mentioning, that this is only one out of many edge cases with the loose equality operator. Maybe you want to check more than just my example above. I bet Kyle Simpson (@getify) could give you some more examples.
Expected behavior:
After a loose equality comparison, TS should not narrow down string | number and string | boolean to string, since a number can equal a string in the edge case 0 == "".
Actual behavior:
After a loose equality comparison, TS narrows down string | number and string | boolean to string, even though this is incorrect, as seen for edge cases like 0 == "".
Playground Link: 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 collegata in Playground usando TypeScript 3.8.3 e confronta il risultato del narrowing con il comportamento dell'uguaglianza debole di JavaScript per 0 == "". Esamina il comportamento dell'equality-narrowing e i relativi casi limite; il lavoro è completato quando il checker non considera più l'esempio come sottoposto a narrowing in modo sicuro quando la coercizione a runtime può rendere vera la comparazione.
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
- 32/100