-
Notifications
You must be signed in to change notification settings - Fork 12.6k
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
Nullish coalescing and conditional type narrowing #48536
Comments
Type narrowing is done only at the level of individual variables, not entire expressions. As such, combining type guards via disjunction |
What @fatcerberus said β¬οΈ |
@fatcerberus does that also apply to something like: const a: string | null | undefined = ...;
if (a ?? '' === '') {
return;
}
const c: string = a; |
@fiddlerwoaroof No, that's not the same thing. |
Ran into this today as well, in a way that Typescript certainly seems like it should handle.
Bummer this can't be handled yet but figured I'd add +1 / another use case here. |
Was this closed as completed because it has been implemented? |
The bulk "Close" action I applied to Design Limitation issues doesn't let you pick what kind of "Close" you're doing, so don't read too much into any issue's particular bit on that. I wish GitHub didn't make this distinction without a way to specify it in many UI actions! The correct state for Design Limitation issues is closed since we don't have any plausible way of fixing them, and "Open" issues are for representing "work left to be done". |
sadge. Thanks |
Suggestion
Conditional + nullish coalescing doesn't seem to reify the type correctly.
π Search Terms
nullish coalescing
nullish coalescing conditional
#43705 sounds maybe related but hard to tell (examples listed don't seem the same)
β Viability Checklist
β Suggestion
Conditional type narrowing through the
||
operator + the use of the nullish coalescing operator should understand each other to reify the type correctly.π Motivating Example
c
should have typestring
but instead it has typestring | undefined
because TS hasn't reasoned that the only way into the block is ifa ?? b
must be non-null.π» Use Cases
Came up in my code where I had two strings and each could be
string | undefined
and I wanted to nullish coalesce but only if one of them was not undefined. Had to use!
as a workaroundThe text was updated successfully, but these errors were encountered: