microsoft / microsoft/TypeScript
`in` operator narrowing (`key in obj`) doesn't work properly when key type is a string union
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
in operator narrowing union
🕗 Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about type narrowing
⏯ Playground Link
💻 Code
// case 1
const KEYS1 = ['a', 'b'] as const;
const obj1 = {a: 'a', b: 'b'};
KEYS1.forEach(key => {
if (key in obj1) console.log(obj1[key]);
});
// case 2
const KEYS2 = ['a', 'b'] as const;
const obj2 = {a: 'a'};
KEYS2.forEach(key => {
if (key in obj2) console.log(obj2[key]); // TS errors when it shouldn't, as we are using `in` narrowing so that the 'b' property access doesn't happen
});
// case 3
const KEYS3 = ['b'] as const;
const obj3 = {a: 'a'}; // KEYS3 does not contain any keys of obj3
KEYS3.forEach(key => {
if (key in obj3) console.log(obj3[key]); // if TS errors in case 2, then it should here too but it doesn't !!!
});
🙁 Actual behavior
- in case 2 TS errors when it shouldn't, as we are using
innarrowing so that there is no incorrect 'b' property access - in case 3 TS doesn't give any errors, when consistency disctates that it should if it did in case 2...
🙂 Expected behavior
Typescript shouldn't detect any errors in case 2. The type narrowing with the in operator ensures that we are only accessing properties that actually exist.
Additional information about the issue
No response
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 il TypeScript Playground collegato e riproduci i tre casi dell’operatore in nell’issue. Traccia il restringimento dei tipi del compilatore e il comportamento dell’accesso alle proprietà indicizzate, quindi aggiungi o aggiorna un test di regressione in modo che il caso 2 venga accettato, mentre il caso 3 venga gestito in modo coerente.
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
- 45/100