How does the compiler use 'never' to achieve exhaustiveness checking in a switch statement over a union type?
Short answer
After a switch statement has handled every known member of a union (via case blocks for each discriminant value), the TYPE of the variable in a trailing default case narrows down to 'never' — because every possible value has already been accounted for, leaving logically zero…
Advertisement
AModel answer
After a switch statement has handled every known member of a union (via case blocks for each discriminant value), the TYPE of the variable in a trailing default case narrows down to 'never' — because every possible value has already been accounted for, leaving logically zero remaining possibilities — and assigning that never-typed value to a never-typed parameter (like assertNever) triggers a compile error only if a case was actually missed.
type Shape = { kind: 'circle' } | { kind: 'square' };
function handle(shape: Shape) {
switch (shape.kind) {
case 'circle': return 'round';
case 'square': return 'angular';
default:
const exhaustiveCheck: never = shape; // errors only if a case is missing
throw new Error(`Unhandled: ${exhaustiveCheck}`);
}
}Real-world example
Building a compile-time safety net that fails the build if a new Shape variant is added without updating every relevant switch statement.
Likely follow-ups
- What specific compiler error message appears if you add a new union variant and forget to handle it here?
Related topics