What Exhaustive Matching Means
You'll learn: How to use TypeScript's type system to ensure you handle every possible variant in a union type, catching missing cases at compile time.
The Core Idea
Exhaustive matching means you've covered all possible cases in a union type. TypeScript can verify this for you automatically — if you forget to handle a variant, the compiler will catch it. This is incredibly powerful for catching bugs before runtime, especially as your code evolves.
Think of it like a safety checklist: if your union has three possible states, exhaustive matching ensures you've written code to handle all three. Miss one? TypeScript raises a red flag.
How It Works
You've already seen discriminated unions and narrowing. Exhaustive matching builds on those concepts by using the never type as a compile-time trap.
The pattern: after narrowing through all expected cases, assign the remaining value (which should be "nothing left") to a variable typed as never. If TypeScript allows this without error, you've handled everything. If TypeScript complains that a specific type isn't assignable to never, you missed a case.
Example pattern:
type Status = { type: 'success' } | { type: 'error' } | { type: 'loading' };
function handle(status: Status) {
if (status.type === 'success') {
// handle success
} else if (status.type === 'error') {
// handle error
} else {
const exhaustiveCheck: never = status; // If you forgot 'loading', error here!
}
}
If you add a fourth variant to Status later but forget to update handle(), TypeScript will immediately flag the problem.
Key Takeaway: Exhaustive matching uses never to verify at compile time that you've handled every variant in a union, preventing bugs when types change.