typescript / intermediate
Snippet
Ensuring Complete Switch Branches with Never Exhaustiveness Checks
Passing a fallback variable to a function accepting only 'never' forces a compile-time error if any union member is left unhandled in conditional branching.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
type UserRole = 'admin' | 'editor' | 'viewer';function assertUnreachable(x: never): never {throw new Error(`Unhandled case: ${JSON.stringify(x)}`);}function getPermissions(role: UserRole): string[] {switch (role) {case 'admin':return ['create', 'read', 'update', 'delete'];case 'editor':return ['create', 'read', 'update'];case 'viewer':return ['read'];default:return assertUnreachable(role);}}
Breakdown
1
function assertUnreachable(x: never): never {
Accepts only the bottom type 'never', which is assignable only if all possibilities were narrowed away.
2
return assertUnreachable(role);
Triggers a compile error if a new UserRole member is added without adding a matching switch case.