Type Narrowing: Teaching TS to Reason

Type Narrowing: Teaching TS to Reason in JavaScript: Say a value could be a . Inside your function you can't call on it — TypeScript stops you, because numbers…

Concept Explanation

Say a value could be a string | number. Inside your function you can't call .toUpperCase() on it — TypeScript stops you, because numbers don't have that method. Narrowing is how you prove to the compiler "in this branch, it's definitely a string," unlocking the string methods safely.

It's a conversation: you write an if check, TypeScript follows your logic, and inside the block it narrows the type automatically. This "control-flow analysis" is one of TypeScript's smartest features.


Syntax or Core Structure

function format(value: string | number) {
  if (typeof value === "string") {
    return value.toUpperCase(); // TS knows it's a string here
  }
  return value.toFixed(2);      // ...and a number here
}

Other narrowing tools:

if (pet instanceof Dog) pet.bark();  // class check
if ("wings" in animal) animal.fly(); // property check
if (value !== null) value.trim();    // null guard

Real World Example

Discriminated Unions: Give each shape a shared "tag" and TS narrows on it:

type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "square"; side: number };

function area(s: Shape) {
  if (s.kind === "circle") return Math.PI * s.radius * s.radius;
  return s.side * s.side; // TS knows it's a square
}

Common Mistakes

  • Trusting any: any skips narrowing entirely — you lose all the safety.
  • Forgetting the null Case: With strict on, TS forces you to guard null/undefined before use.
  • Wide Return Types: If a function can return several shapes, model them as a union so callers can narrow.

Best Practices

  • Tag Your Unions: A shared kind field makes narrowing trivial and exhaustive.
  • Use Type Guards: For reusable checks, write a function returning x is Dog (a "type predicate").
  • Handle Every Branch: Add a default that assigns to never so a new variant becomes a compile error.

Practice Exercises

  1. The Formatter: Write a function taking string | number that upper-cases strings and rounds numbers.
  2. The Shape: Build a discriminated union of "circle" and "rectangle" and compute each area.
  3. The Guard: Write a type predicate isString(x): x is string and use it to narrow an unknown.