×

typescript · level 2 · unit 2 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

is how you prove which type you have.

A string | number value might be either, so the checker only lets you do things that work on both. Call .toUpperCase() on it and you get TS2339, because numbers have no such method.

So ask first. Inside if (typeof code === "string"), the checker knows code is a string, and string methods work. In the else, only number is left. This is narrowing: each check makes the list of possible types shorter.

Checking !== null narrows too. After if (answer !== null), a string | null is a plain string.

function label(code: string | number): string {
  if (typeof code === "string") {
    return code.toUpperCase();
  } else {
    return `No. ${code}`;
  }
}
console.log(label("b12"));
console.log(label(7));

Narrowing only lasts inside the block where the check was made.