Exhaustiveness Checking with Discriminated Unions
You'll learn how to use never-based checks to guarantee that every variant of a discriminated union is handled in your logic.
The Problem: Silent Unhandled Cases
When you work with discriminated unions, you might handle all current variants in a switch statement or if-else chain. But what happens when someone adds a new variant later? Without proper checking, your code might silently fail to handle it—a bug waiting to happen.
The never Trick
TypeScript's never type represents values that can never exist. By assigning the unhandled union remnant to a never type, you force a compile-time error if any case isn't covered.
Here's the pattern:
type Status =
| { kind: 'loading' }
| { kind: 'success'; data: string }
| { kind: 'error'; message: string };
function handleStatus(status: Status) {
switch (status.kind) {
case 'loading':
console.log('Loading...');
break;
case 'success':
console.log(status.data);
break;
case 'error':
console.log(status.message);
break;
default:
const exhaustiveCheck: never = status;
throw new Error(`Unhandled case: ${exhaustiveCheck}`);
}
}
In the default branch, we assign status to a variable of type never. Since all cases are handled, TypeScript narrows status to never in the default branch—the assignment succeeds.
If you later add a fourth variant (like { kind: 'idle' }) without handling it, TypeScript will complain at the never assignment because status could still be that new variant.
Key Takeaway: By assigning the leftover union to a never type in the default case, TypeScript enforces exhaustive handling—any missing variant immediately causes a compile error.