Exhaustive Switching on State
What you'll learn: How discriminated unions force you to handle every possible state explicitly with exhaustive checks.
When you model application state with discriminated unions (like we've done in previous lessons), TypeScript can enforce that you handle every possible variant. This is called exhaustive switching — ensuring your code accounts for all cases without accidentally leaving gaps.
How Discriminated Unions Enable Exhaustiveness
Discriminated unions define a closed set of possible states. Because TypeScript knows exactly which variants exist, it can verify that your switch statement or if/else chain covers them all.
type LoadingState =
| { status: 'idle' }
| { status: 'loading' }
| { status: 'success'; data: string }
| { status: 'error'; error: Error };
function render(state: LoadingState): string {
switch (state.status) {
case 'idle':
return 'Not started';
case 'loading':
return 'Loading...';
case 'success':
return `Data: ${state.data}`;
case 'error':
return `Error: ${state.error.message}`;
}
// TypeScript knows all cases are handled
}
The Never Check Pattern
To make exhaustiveness compile-time enforced, assign the remaining value to never after all cases:
function render(state: LoadingState): string {
switch (state.status) {
case 'idle':
return 'Not started';
case 'loading':
return 'Loading...';
case 'success':
return `Data: ${state.data}`;
// Forgot 'error' case!
}
const exhaustive: never = state; // ❌ Error: Type 'error' not assignable to never
return exhaustive;
}
If you add a new state variant later, TypeScript immediately flags every switch that doesn't handle it.
Key takeaway: Discriminated unions plus exhaustive checks ensure you can never forget to handle a state, making refactoring safe and bugs impossible to miss at compile time.