0Pricing
TypeScript Academy · Lesson

typeof, equality, truthiness narrowing

Use typeof, strict equality, and truthiness to narrow union types without unsafe casts.

Intro

Goal: Narrow broad union types down to exact types using typeof, strict equality, and truthiness. This unlocks safe property/method access.

typeof narrowing

typeof narrows primitives (string, number, boolean, bigint, symbol, undefined). Use it to branch safely.

function printLen(x: string | number) {
  if (typeof x === "string") {
    console.log(x.length); // x is string
  } else {
    console.log(x.toFixed(2)); // x is number
  }
}

printLen("TS");
printLen(3.14);

All lessons in this course

  1. typeof, equality, truthiness narrowing
  2. in, instanceof, discriminated unions
  3. Exhaustiveness with never (intro)
← Back to TypeScript Academy