The code below unexpectedly produces an error, despite the type of a
having been narrowed to string
on the line const b = a
.
Note that if I assign a
to b
, b
does not suffer from the same problem.
function test(a: string | undefined) {
if (a) {
const b = a
const x = false && a.length // Error: 'a' is possibly 'undefined'
const y = false && b.length // No error
}
}
Why is this happening? Obviously this code is not very useful as both x
and y
are just false
, but I sometimes prepend false&&
as a way of easily commenting out code (in JSX, so using traditional comments is more tricky), but I end up getting these errors.
As mentioned by @jcalz in the comments:
This is ms/TS#26914. After false && you're in unreachable code and all narrowings reset
You can use ()
as a workaround:
function test(a: string | undefined) {
if (a) {
const b = a;
const x = false && a.length; // Error
const y = (false) && b.length; // OK
const z = (false) && a.length; // OK
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With