You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
null comparison fails in switch statement with --strictNullChecks #8971
In your first example the checker complains about the null case because control flow analysis has narrowed the type of foo to number and thus concluded (rightly so) that foo is can't be null. It is similar to the following:
letx: string|number;x="foo";// x is known to be a string in the followingswitch(x){case0: // Error, x can't be numbercase1: // Error, x can't be numbercase"foo":
case"bar":
}
Now, the thing that's confusing is that we allow the foo === null in the if statement in your second example. See #8452 for the reasoning on why that's permitted. We should probably extend that to switch statements as well.
The reason it works when you insert the if statement is that we take that statement as an assertion that x could be null at that point, even though control flow analysis has concluded it couldn't. See #8548 for the reasoning on that feature.
To sum up, the issue here is that we should always allow null and undefined cases in switch statements to be consistent with #8452.
Activity
ahejlsberg commentedon Jun 5, 2016
In your first example the checker complains about the
nullcase because control flow analysis has narrowed the type offootonumberand thus concluded (rightly so) thatfoois can't benull. It is similar to the following:Now, the thing that's confusing is that we allow the
foo === nullin theifstatement in your second example. See #8452 for the reasoning on why that's permitted. We should probably extend that to switch statements as well.The reason it works when you insert the
ifstatement is that we take that statement as an assertion thatxcould be null at that point, even though control flow analysis has concluded it couldn't. See #8548 for the reasoning on that feature.To sum up, the issue here is that we should always allow
nullandundefinedcases in switch statements to be consistent with #8452.bmayen commentedon Jun 5, 2016
Thanks for the explanation!