The Basic Exhaustive Check Pattern
You'll learn how to create a helper function that uses never to catch missing cases in switch statements at compile time.
The Core Idea
When you're handling a discriminated union with a switch statement, you want TypeScript to force you to handle every possible case. The exhaustive check pattern uses a function that only accepts never as its argument. If you haven't handled all cases, TypeScript will still have a concrete type left over — and passing that to a function expecting never will trigger a compile error.
Think of it like a mandatory final inspection at the end of an assembly line. If any product is still on the conveyor belt when it reaches the inspection station (which expects nothing), the alarm goes off.
The Helper Function
You create a simple function that accepts only never:
function assertNever(value: never): never {
throw new Error(`Unexpected value: ${value}`);
}
This function has two important characteristics:
- Its parameter is typed as
never(only accepts the impossible) - Its return type is
never(never returns normally)
The Pattern in Action
type Status = "pending" | "success" | "error";
function handleStatus(status: Status): string {
switch (status) {
case "pending":
return "Loading...";
case "success":
return "Done!";
case "error":
return "Failed!";
default:
assertNever(status); // status is never here
}
}
If all cases are handled, status in the default branch has type never (because no values remain). The function call succeeds at compile time.
What Happens When You Forget a Case
function handleStatus(status: Status): string {
switch (status) {
case "pending":
return "Loading...";
case "success":
return "Done!";
// Oops! Forgot "error"
default:
assertNever(status); // ERROR: Argument of type 'string' is not assignable to parameter of type 'never'
}
}
Because you didn't handle "error", the status in the default branch still has type "error" — which cannot be assigned to never. TypeScript catches this immediately.
Key Takeaway: The exhaustive check pattern uses a function accepting never to detect unhandled union cases at compile time, making your switch statements future-proof when new variants are added.