Skip to content

[FER] Type guard on left-hand-side of operator in #48149

Closed as not planned
Closed as not planned
@yw662

Description

@yw662

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    DeclinedThe issue was declined as something which matches the TypeScript visionSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions