microsoft / microsoft/TypeScript
`in` operator narrowing (`key in obj`) doesn't work properly when key type is a string union
Open
Nobody has claimed this yet.
Domain: check: Control Flow
Possible Improvement
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 1d 19h
- Merged PRs (30d)
- 117
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
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
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the linked TypeScript Playground and reproduce the three in operator cases in the issue. Trace the compiler's type narrowing and indexed property access behavior, then add or update a regression test so case 2 is accepted while case 3 is handled consistently.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100