typescript / intermediate
Snippet
Managing Asynchronous State with Discriminated Unions
Discriminated unions combine a common literal property ('status') across union members to allow TypeScript to narrow down payload types automatically inside control flow blocks.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
type AsyncState<T> =| { status: 'idle' }| { status: 'loading' }| { status: 'success'; data: T }| { status: 'error'; error: Error };function renderState<T>(state: AsyncState<T>): string {switch (state.status) {case 'idle':return 'Waiting to start...';case 'loading':return 'Fetching data...';case 'success':return `Data loaded: ${JSON.stringify(state.data)}`;case 'error':return `Error occurred: ${state.error.message}`;}}
Breakdown
1
type AsyncState<T> =
Defines a generic union type representing mutually exclusive state variants.
2
| { status: 'success'; data: T }
Combines the discriminant status property with payload data of type T.
3
switch (state.status) {
Evaluates the discriminant property to narrow down the specific variant.
4
case 'success': return `Data loaded: ${JSON.stringify(state.data)}`;
Inside this branch TypeScript narrows state to the success variant allowing safe access to data.