-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Type narrowing/guard together with nullish coalescing/optional chaining #38136
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
A simple workaround is:
|
Hehe, I can't believe I didn't see that, thanks! 😄 Would still be great if type narrowing could work with nullish coalescing though |
Narrowing works with nullish coalescing.
We can see that, in order to reach the default branch, |
It also doesn't work with optional chaining: enum MenuType { EatIn, TakeAway }
declare function unreachable (value: never): never
declare let filter: { menuType: MenuType | null | undefined } | null | undefined
// Works :)
if (filter?.menuType != null) {
switch (filter.menuType) {
case MenuType.EatIn: console.log(1); break
case MenuType.TakeAway: console.log(2); break
default: unreachable(filter.menuType)
}
}
// Doesn't work :(
switch (filter?.menuType) {
case MenuType.EatIn: console.log(1); break
case MenuType.TakeAway: console.log(2); break
case null: console.log(3); break
case undefined: console.log(3); break
default: unreachable(filter.menuType)
} @ilogico I believe that this demonstrates a case where I have not essentially created a new variable? Especially since it works when doing |
You're not creating a new variable, but you are creating a new value. In any case, this has nothing to do with nullish coalescing or optional chaining. If replace one with |
Ahhhhh, I see now, thanks for the explanation! |
Uh oh!
There was an error while loading. Please reload this page.
TypeScript Version: 3.9.0-dev.20200422
Search Terms: type narrowing guard nullish coalescing switch exhaustive optional chaining
Code
Expected behavior:
I expected TypeScript to figure out that I have covered all possible values of
menuTypeFilter
, and thus let me have an unreachabledefault
case.Actual behavior:
Playground Link: Playground Link
Related Issues: (I thought this would have come up but didn't manage to find another issue)
Motivation: I would like to both 1) get an error if the enum ever expands in the future, and 2) handle
null
andundefined
in the same way.The text was updated successfully, but these errors were encountered: