Lesson 1.2

Unions, intersections, and narrowing

A union says a value is one of several types; control flow analysis then narrows it as you check.

3mIntermediate23.6k students

Overview

Let the branch prove the type

A union says a value is one of several types; control flow analysis then narrows it as you check. Inside an if branch, the compiler knows more than it did outside — that is the mechanism behind almost all idiomatic TypeScript.

A discriminated union, where each member carries a distinct literal tag, is the most reliable form. Switching on the tag narrows exhaustively, and adding a new member turns every unhandled switch into a compile error.

When a check is too clever for the compiler to follow, a type predicate lets you assert the outcome. It is a promise you are making, so the body must genuinely verify what it claims.

  • typeof narrows primitives
  • in narrows by property presence
  • a literal discriminant narrows object unions exhaustively

In this lesson you will:

  • Model a value that has several shapes
  • Narrow with typeof, in, and discriminants
  • Write a type predicate for a custom check

Resources

Previous Lesson
Next Lesson
Unions, intersections, and narrowing — TypeScript Deep Dive — Vertex