Closed as not planned
Description
Suggestion
Operator in
can narrow the right-hand-side value, but it could also narrow the left-hand-side:
const a = {
a: 1, b: 2, c: 3
} as const
const f = (char: keyof typeof a) => {}
const char = ['c', 'd'][Math.round(Math.random())]
if(char in a) {
f(char)
}
char
is 'c' | 'd'
(or string
), but if char in a
is true, it should be able to narrow to 'c'
.
🔍 Search Terms
type guard
, narrow
, operator in
✅ Viability Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
⭐ Suggestion
As shown above: narrow also left-hand-side when possible.
📃 Motivating Example
As shown above
💻 Use Cases
As shown above