Surprisingly, the code snippet below is generating an error, even though the variable a
has been narrowed down to type string
in the line const b = a
.
It's worth noting that when I assign a
to b
, b
does not encounter the same issue.
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
}
}
What could be causing this unexpected behavior? This code example might not be particularly functional since both x
and y
are simply false
. However, I sometimes use false&&
as a way to easily comment out code (especially in JSX where traditional commenting can be more complex), but then these errors pop up.