Course contentsShow
← TypeScript
Lesson 393 of 1,7969. Union TypesFree lesson

typeof Guards for Primitive Unions

Using typeof checks to narrow unions of string, number, boolean, and other primitives.

typeof Guards for Primitive Unions

You'll learn how to use typeof checks to safely narrow down union types containing primitive values.

The Core Idea

When a variable could be one of several primitive types (like string | number), TypeScript doesn't know which type it actually is at any given moment. The typeof operator lets you check which primitive type you're dealing with at runtime, and TypeScript's control flow analysis automatically narrows the type inside that check.

Think of it like sorting mail: if a package could contain either a book or a DVD, you check its shape before deciding which shelf to put it on. The typeof guard is your shape-checker for primitive values.

How It Works

function formatValue(value: string | number): string {
  if (typeof value === "string") {
    // TypeScript knows value is string here
    return value.toUpperCase();
  } else {
    // TypeScript knows value must be number here
    return value.toFixed(2);
  }
}

TypeScript tracks which type remains after each check. When you test typeof value === "string", the if block narrows value to string, and the else block automatically knows it must be number.

Works with Multiple Primitives

function process(input: string | number | boolean): void {
  if (typeof input === "string") {
    console.log(input.length);
  } else if (typeof input === "number") {
    console.log(input.toFixed(1));
  } else {
    console.log(input ? "yes" : "no");
  }
}

Each typeof check peels away possibilities, progressively narrowing what remains.

Key Takeaway: Use typeof guards to check and narrow primitive union types, enabling TypeScript to provide type-safe access to type-specific properties and methods within each branch.