microsoft / microsoft/TypeScript
Non-null assertion operator whitespace allowances can create confusing conditional statements
Nessuno ha ancora preso questa issue.
- Lingua principale
- Go
- Stelle
- 111k
- Fork
- 14.3k
- Merge medio
- 1g 19h
- PR unite (30g)
- 117
Descrizione
🔎 Search Terms
You can write a non-null assertion operator with whitespace after a variable name and no white space before certain keywords such as in and instanceof and the type checker doesn't fail but instead strips the operator creating the opposite condition as it appears.
To a someone not familiar with TypeScript/JavaScript key !in obj reads like if key not in obj . To them this might be if the tsc treated key !== 'a' as key == 'a'
🕗 Version & Regression Information
- This changed between versions N/A and N/A
- This changed in commit or PR N/A
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about Common "Bugs" That Aren't Bugs
- I was unable to test this on prior versions because N/A
⏯ Playground Link
💻 Code
const foo: {a?: string} = {a: 'bar'};
const key = 'a' as const;
if (key !in foo) {
// non-null operator stripped and key exists in obj
console.log(foo[key]);
}
if (foo !instanceof Object) {
// non-null operator stripped and obj is Object
console.log(typeof foo);
}
🙁 Actual behavior
The TSC stripped the non-null assertion, the operator should not be considered a non-null operator at all in this situation.
🙂 Expected behavior
I would expect a syntax error in this situation.
Additional information about the issue
This is a real problem not just hypothetical, I noticed a discussion started by a person learning typescript complaining about how their code was evaluating true regardless of the "negation operator" being used before the in keyword.
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 gli esempi dal link di Playground con tsc, concentrandoti sugli spazi vuoti prima di in e instanceof. Traccia come vengono analizzate e validate queste espressioni, quindi aggiungi una copertura di regressione che dimostri che le forme producono un errore di sintassi invece di rimuovere l’asserzione non-null.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- javascript, 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
- 35/100