- All Courses
- TypeScript Deep Dive
- The Type System Underneath
- Unions, intersections, and narrowing
Unions, intersections, and narrowing
A union says a value is one of several types; control flow analysis then narrows it as you check.
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
Notes are not saved yet — they clear when you leave this page.
Structural typing and assignability
12m
Literal types and const assertions
6m