-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Narrow on else branch of multi-conditional guard #5427
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
Conversation
Worth noting: this doesn't fix #4874, but it changes the behaviour:
|
Can you update the comment in tests/cases/conformance/expressions/typeGuards/typeGuardOfFormExpr1OrExpr2.ts in the same way that you did with the one in checker.ts? |
From reading #1270, it sounds like the problem is that Wouldn't the correct fix be to the code that removes members from the union? |
The The narrowing that needs to be done for the correct behavior is this: // Narrowing occurs only if target type is a subtype of variable type
if (typeof strOrNum === "boolean") {
//...
} changes - specifically, in this scenario we decide that an empty union means the type should not be narrowed, but if we allow empty set returns from the type quality narrowing expression, then we get an empty set within this block rather than the original type. Now, in my mind, narrowing to an empty set of types seems fine - so if that change in behavior is desirable, it certainly seems like the preferable fix. |
Let's hold this change until we have a chance to vet it in a design discussion. Narrowing to the empty set makes sense to me in most cases, but there may be good reasons not to. Specifically, I think the case in #4029 should be empty set: var x: string | number;
if(typeof x === 'string') {
}
else if(typeof x === 'number') {
}
else {
// some kind of fallback... x should be {} not string | number
} |
Superseded by #5442. |
Fixes #1270.
Removing the short-circuiting logic "shortcut" (which actually did an extra narrow when it doesn't strictly need to) fixes the issue.