Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript undefined error despite type narrowing occuring

Tags:

typescript

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.

like image 888
Laurent Avatar asked Sep 02 '25 03:09

Laurent


1 Answers

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
  }
}
like image 60
Remo H. Jansen Avatar answered Sep 04 '25 23:09

Remo H. Jansen