Exhaustive Switch With Never Checks
Force every enum member to be handled by routing the default branch through a never assignment, so adding a variant fails the build.
Code
type JobState = 'queued' | 'running' | 'succeeded' | 'failed';
function describe(state: JobState): string {
switch (state) {
case 'queued':
return 'waiting for a worker';
case 'running':
return 'work in progress';
case 'succeeded':
return 'finished successfully';
case 'failed':
return 'ended with an error';
default: {
// 新增成员时此处编译失败,强制补分支
const unreachable: never = state;
throw new Error('unhandled state: ' + String(unreachable));
}
}
}
const states: JobState[] = ['queued', 'running', 'succeeded', 'failed'];
for (const state of states) {
console.log(state, '=>', describe(state));
}Output
Captured from a sandboxed run of this snippet in the build pipeline.
queued => waiting for a worker
running => work in progress
succeeded => finished successfully
failed => ended with an errorInside the code
One way to read it: the function describe, doing all the work.
Iteration happens inside for (const state of states) — everything outside it runs once. When the guard condition holds, Error is thrown rather than a bogus value returned.
Applying it
The primary signature is function describe(state: JobState)
Statements that matter
throw new Error('unhandled state: ' + String(unreachable));
return 'finished successfully';
return 'waiting for a worker';
Interactive Tools for This Topic
FAQ
- How does the snippet fail?
- It throws `Error` before any real work runs — handle it at the call site or let it propagate deliberately.
- Is a package install part of the setup?
- No. Installation is unnecessary because only built-in APIs are used. The file defines `describe` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.