0Pricing
TypeScript Academy · Lesson

typeof and Truthiness Narrowing

Use typeof checks to narrow primitive types.

Welcome

TypeScript narrows union types inside conditional blocks. `typeof` checks and truthiness checks are the most common narrowing techniques.

typeof Narrowing

Use `typeof` to check primitive types. TypeScript understands typeof checks and narrows the type inside the block.
function process(val: string | number) {
  if (typeof val === 'string') {
    return val.toUpperCase(); // val: string
  }
  return val.toFixed(2); // val: number
}

All lessons in this course

  1. typeof and Truthiness Narrowing
  2. instanceof and in Narrowing
  3. User-Defined Type Guard Functions
  4. Exhaustiveness Checking with never
← Back to TypeScript Academy