Skip to content

Article: Why narrowing without a discriminant needs the 'in' operator #82

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

Open
JoshuaKGoldberg opened this issue Aug 15, 2022 · 0 comments
Assignees
Labels
type: article Adding a new article .mdx file

Comments

@JoshuaKGoldberg
Copy link
Collaborator

I actually don't remember the historical reasons for this is the case, but have the rule memorized...

In general, TypeScript won't let you access properties of a value that aren't defined in all possible types the value might be. So you can't do things like:

declare const value: { a: string } | { b: string };

value.a;
//    ~
// Property 'a' does not exist on type '{ a: string; } | { b: string; }'.
//   Property 'a' does not exist on type '{ b: string; }'.

However, you can do an existence check with the in operator. That will work as a form of type narrowing:

declare const value: { a: string } | { b: string };

if ('a' in value) {
  value.a; // Ok
  // ^? { a: string }
}

https://discord.com/channels/508357248330760243/942074070860705852/1008521509532356649

@JoshuaKGoldberg JoshuaKGoldberg added the type: article Adding a new article .mdx file label Aug 15, 2022
@JoshuaKGoldberg JoshuaKGoldberg self-assigned this Aug 15, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type: article Adding a new article .mdx file
Projects
None yet
Development

No branches or pull requests

1 participant