typescript / expert
Snippet
Compile-Time Exhaustive Union Control Flow Assertion
Exhaustive type narrowing leverages TypeScript's `never` type to verify that all variants of a discriminated union are handled in control flow statements. Adding new union variants will cause a compile-time error in default branches calling the unreachable assertion.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
type Command =| { type: "START"; payload: { timestamp: number } }| { type: "STOP"; payload: { reason: string } };function assertUnreachable(x: never): never {throw new Error(`Unhandled union variant: ${JSON.stringify(x)}`);}function processCommand(cmd: Command): string {switch (cmd.type) {case "START":return `Starting at ${cmd.payload.timestamp}`;case "STOP":return `Stopping: ${cmd.payload.reason}`;default:return assertUnreachable(cmd);}}
Breakdown
1
type Command =
Defines a discriminated union type of valid application commands.
2
function assertUnreachable(x: never): never {
Defines a function parameter of type never that fails compilation if any variant remains unhandled.
3
throw new Error(`Unhandled union variant: ${JSON.stringify(x)}`);
Provides runtime safety in case unexpected data bypasses compile-time checks.
4
function processCommand(cmd: Command): string {
Implements the command processing logic using switch narrowing.
5
default:
Reaches default branch only if all switch cases fail to exhaust the union type.
6
return assertUnreachable(cmd);
Passes the narrowed command variable to verify type exhaustiveness at compile time.