Open
Description
π 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
in
narrowing 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