Exhaustiveness Checking with never
What you'll learn: How to use the never type to catch missing cases in discriminated union handling at compile time.
When working with discriminated unions, you want to be sure you've handled every possible variant. TypeScript's never type provides an elegant way to enforce this at the type level.
The Core Idea
After narrowing through all known union variants (using switch or if/else chains), any leftover value should be impossible. If you try to assign this leftover to a variable typed as never, TypeScript will allow it—unless you've missed a case. Then it complains, because the value isn't actually impossible.
Think of never as a compile-time trap: if any real value can reach it, you forgot something.
How It Works in Practice
After handling all discriminated union cases, add a final branch that assigns the remaining value to a variable of type never. If you've truly covered everything, the code is unreachable. If you haven't, TypeScript errors immediately.
type Result =
| { kind: 'success'; value: number }
| { kind: 'error'; message: string };
function handle(result: Result): string {
switch (result.kind) {
case 'success':
return `Got ${result.value}`;
case 'error':
return `Failed: ${result.message}`;
default:
const _exhaustive: never = result; // ✓ compiles
return _exhaustive;
}
}
If you add a new variant to Result but forget to handle it, result in the default branch won't be never anymore—it'll be the missing variant, and TypeScript will error.
Key Takeaway: Assign leftover discriminated union values to a never-typed variable to enforce exhaustiveness checking and catch missing cases at compile time.