Compile-Time vs Runtime Guarantees
You'll learn: How TypeScript's exhaustive checks protect you at compile-time while understanding when runtime defenses are still necessary.
The Two Layers of Safety
When you use exhaustive checking with never and discriminated unions, TypeScript catches missing cases before your code runs. This is a compile-time guarantee—the TypeScript compiler refuses to build your code until you handle all possibilities.
However, TypeScript only exists during development. Once compiled to JavaScript, all type information disappears. This means compile-time guarantees don't protect against unexpected runtime values.
When Compile-Time Isn't Enough
Consider a discriminated union with an exhaustive check:
type Status = { kind: 'success' } | { kind: 'error' };
function handle(status: Status) {
switch (status.kind) {
case 'success':
return 'OK';
case 'error':
return 'Failed';
default:
assertNever(status); // Compile-time: all cases covered
}
}
This works perfectly if the data comes from TypeScript code. But what if status comes from:
- An API response
- User input
- A database
- A third-party library
At runtime, you might receive { kind: 'pending' }, which violates your type but wasn't caught by TypeScript.
Defense in Depth
For external data, combine both approaches:
function handleExternal(data: unknown) {
// Runtime validation first
if (typeof data === 'object' && data !== null && 'kind' in data) {
const status = data as Status; // Now trust compile-time checking
return handle(status);
}
throw new Error('Invalid status');
}
Key Takeaway: Exhaustive checks guarantee compile-time safety within your typed code, but runtime validation is essential when data crosses boundaries from the outside world.