microsoft / microsoft/TypeScript
`in` operator narrowing (`key in obj`) doesn't work properly when key type is a string union
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Go
- Sterne
- 111k
- Forks
- 14.3k
- Ø Merge
- 1 T. 19 Std.
- Gemergte PRs (30 T.)
- 117
Beschreibung
🔎 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
Beitragsleitfaden
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
Beginne mit dem verlinkten TypeScript Playground und reproduziere die drei Fälle des in-Operators aus dem Issue. Verfolge die Typverengung des Compilers und das Verhalten beim Zugriff auf indizierte Eigenschaften und füge anschließend einen Regressionstest hinzu oder aktualisiere ihn, sodass Fall 2 akzeptiert wird, während Fall 3 konsistent behandelt wird.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- typescript
- Bereich
- compilers
- Issue-Typ
- Bug
- Schwierigkeit
- 4/5
- Geschätzter Aufwand
- 3-5 Tage
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 45/100