Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
5 tasks done
yw662 opened this issue Mar 7, 2022 · 2 comments
Closed
5 tasks done

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

yw662 opened this issue Mar 7, 2022 · 2 comments
Labels
Declined The issue was declined as something which matches the TypeScript vision Suggestion An idea for TypeScript

Comments

@yw662
Copy link

yw662 commented Mar 7, 2022

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

@yw662 yw662 closed this as completed Mar 7, 2022
@yw662 yw662 reopened this Nov 9, 2022
@RyanCavanaugh
Copy link
Member

This wouldn't be sound. See https://stackoverflow.com/questions/55012174/why-doesnt-object-keys-return-a-keyof-type-in-typescript

@RyanCavanaugh RyanCavanaugh added Suggestion An idea for TypeScript Declined The issue was declined as something which matches the TypeScript vision labels Nov 10, 2022
@typescript-bot
Copy link
Collaborator

This issue has been marked as "Declined" and has seen no recent activity. It has been automatically closed for house-keeping purposes.

@typescript-bot typescript-bot closed this as not planned Won't fix, can't repro, duplicate, stale Jun 21, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Declined The issue was declined as something which matches the TypeScript vision Suggestion An idea for TypeScript
Projects
None yet
Development

No branches or pull requests

3 participants