Closed
Description
TypeScript Version: 2.1.5
Code
--strictNullChecks
should be enabled.
const nil = null;
// Compile error:
// "Operator '<' cannot be applied to types 'null' and 'number'"
if (nil < 10) { }
// Use function to trick the type narrowing
function test(): number | null {
return null;
}
const n = test();
// OK
if (n < 1) { }
Expected behavior:
Both comparisons should generate a compilation error.
Actual behavior:
The first comparison (nil < 10) fails to compile (as expected), but the second one (n < 1) compiles successfully.
It seems odd that the same operation (less-than number) is not allowed for null
(what is completely fine), but allowed for union type that includes null
. If there are some solid reasons to behave this way, I think they should be mentioned in the language guide (can't find something about it).