-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Implement type narrowing for optional chaining operator on unions #56440
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
Comments
Want to see something fun? // not a type error:
function doTheThing(): { someResult: { foo: 'bar' } } | { error: string } {
const err = { error: "fooey", someResult: { foo: 42 } };
return err;
}
// prints a number, not a string.
// worse, itβs not properly recognized as an error!
const res = doTheThing();
console.log('someResult' in res ? res.someResult.foo : `err: ${res.error}`); Types are not exact (see #12936) and |
Ah, thanks, I corrected that.
That is unfortunate. I didn't think to look in closed issues as this seems equivalent to using 'in', just shorter. Perhaps they will reconsider
Even so, it's no worse than 'in', just quicker. Coders need to account for the various scenarios either way. |
It's indeed no worse than |
That seems unlikely. See #33736 (comment), in particular the last paragraph where the equivalence to
|
It's hard to imagine anything has changed since #56264 was filed less than a month ago. |
This issue has been marked as "Duplicate" and has seen no recent activity. It has been automatically closed for house-keeping purposes. |
π Search Terms
"type narrowing", "optional chaining operator", "unions"
β Viability Checklist
β Suggestion
Infer a union object's type following the optional chaining operator
π Motivating Example
Say I have the result of an API call that returns some result or an error like this:
If I want to use the value of foo if it exists, it would be quicker to use optional chaining rather than an if statement to determine the type of response. Eg.
const foo = res.someResult?.foo ?? 'no result';
as opposed to
or
const foo = 'someResult' in res ? res.someResult.foo : 'no result';
π» Use Cases
Further examples:
https://stackoverflow.com/questions/58974640/typescript-property-does-not-exist-on-union-type#comment120750095_58974714
The text was updated successfully, but these errors were encountered: