typescript / intermediate
Snippet
Exhaustive Union Handling with Never Type Assertions
When working with discriminated unions, assigning the default switch branch to a function parameter typed as never triggers compile-time type errors whenever new members are added to the union without updating switch cases.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
type UserRole = "admin" | "editor" | "viewer";function assertUnreachable(x: never): never {throw new Error(`Unexpected discriminant value: ${JSON.stringify(x)}`);}function getPermissions(role: UserRole): string[] {switch (role) {case "admin": return ["read", "write", "delete"];case "editor": return ["read", "write"];case "viewer": return ["read"];default: return assertUnreachable(role);}}
Breakdown
1
function assertUnreachable(x: never): never
Defines a helper function expecting the unreachable never type, forcing compile error if any union case remains unhandled.
2
default: return assertUnreachable(role);
Evaluates default branch at compile-time to guarantee exhaustive branch handling.