Search code examples
javascriptstringtypescripttypeof

typescript typeof string doesn't work as expected


Can anybody explain why the second variant doesn't work? Is it a bug?

const prints = (s: string): void => console.log(s);
var x: string | number = Date.now() % 2 ? "test" : 5;

// 1st: working
if (typeof x === "string") {
  prints(x);
}

// 2nd: not working
var typex = typeof x === "string";
if (typex) {
  prints(x);
}

The second variant shows the following error:

Argument of type 'string | number' is not assignable to parameter of type 'string'. Type 'number' is not assignable to type 'string'

TS Playground


Solution

  • As already mentioned at comments, the question is already exists on github: Indirect type narrowing via const and allow storing results of narrowing in booleans for further narrowing