javascript / expert
Snippet
Algebraic Data Types with Exhaustive Pattern Matching
Using Tagged Unions allows for precise modeling of mutually exclusive states in Next.js components. The 'never' type assignment in the default case ensures compile-time safety, forcing developers to handle every possible state branch explicitly.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
type UIState =| { type: 'IDLE' }| { type: 'LOADING' }| { type: 'SUCCESS'; data: string[] }| { type: 'ERROR'; message: string };function render(state: UIState) {switch (state.type) {case 'IDLE': return 'Standby';case 'LOADING': return 'Loading...';case 'SUCCESS': return `Found ${state.data.length} items`;case 'ERROR': return `Error: ${state.message}`;default: {const _exhaustive: never = state;throw new Error(`Unhandled state: ${_exhaustive}`);}}}
nextjs
Breakdown
1
| { type: 'SUCCESS'; data: string[] }
A specific variant of the union type carrying additional payload data.
2
switch (state.type)
Dispatches logic based on the discriminator field 'type'.
3
const _exhaustive: never = state;
TypeScript trick to ensure all cases are covered; will fail to compile if a union member is missing.