Consider the code below:
function f(x : number) {
if (x === 1) {
if (x === 2) {} // error
}
else {
if (x === 1) {} // OK
}
}
The compiler flags an error on x === 2
.
This is because if the code reaches this block, x
must be 1
since x === 1
passed.
And as 1
and 2
are distinct, it's impossible for x
to be both.
Surprisingly, the compiler allows the second x === 1
within the else
statement.
This seems illogical because x
already failed the check for x === 1
in the initial if
.
Since x
cannot simultaneously satisfy x === 1
and !(x === 1)
, the second if
should generate the same error as x === 2
.
How can this happen? Is it an unimplemented feature of complex flow analysis? Is it a bug? Or could there be some hidden logic that ultimately makes sense in this scenario?
Thank you.