Skip to content

Type Narrowing

Medium — good to knowGeneral Dev

ELI5 — The Vibe Check

Type narrowing is TypeScript being a detective. It watches your if-statements and logical checks, then deduces 'ah, at this point in the code, this variable MUST be a string.' It's Sherlock Holmes but for types.

Real Talk

The process by which TypeScript's control flow analysis refines a variable's type to a more specific type based on conditional checks, assignments, and type guard expressions. Type narrowing happens automatically within if/else blocks, switch statements, and after truthiness checks.

Show Me The Code

function format(value: string | number | null) {
  if (value === null) return 'N/A';
  // narrowed to string | number
  if (typeof value === 'string') {
    return value.trim(); // narrowed to string
  }
  return value.toFixed(2); // narrowed to number
}

When You'll Hear This

"TypeScript's narrowing is smart enough to know that after a null check, the value can't be null." / "Use discriminated unions with narrowing — it's the TypeScript sweet spot."

Made with passive-aggressive love by manoga.digital. Powered by Claude.