TypeScript Master (50 Qs)•Part 3: Enterprise Architecture, Compiler Internals & Performance (Senior / Staff)
How do you enforce Exhaustive Type Checking in `switch` statements?
senior LevelCode ExampleFormsPerformanceSystem Design
In Simple Words:
Assigning the unhandled case to a never variable guarantees that if a new member is added to a union, the TypeScript compiler will fail until all cases are handled:
typescript
type Action = "start" | "stop" | "pause";
function handleAction(action: Action) {
switch (action) {
case "start": return 1;
case "stop": return 0;
case "pause": return 2;
default:
const _exhaustiveCheck: never = action; // Error if any Action case is forgotten!
return _exhaustiveCheck;
}
}