snippettypescriptModeratepending
TypeScript discriminated unions -- type-safe state machines
Viewed 0 times
discriminated uniontagged unionstate machineexhaustive check
browsernodejs
Problem
Representing loading/success/error with booleans leads to impossible states. Need mutually exclusive states.
Solution
Use discriminated unions with a literal status field. TypeScript narrows in switch/if blocks.
Code Snippets
Discriminated union for async state
type AsyncState<T> =
| { status: 'idle' }
| { status: 'loading' }
| { status: 'success'; data: T }
| { status: 'error'; error: Error };
function render<T>(state: AsyncState<T>) {
switch (state.status) {
case 'idle': return null;
case 'loading': return <Spinner />;
case 'success': return <Data value={state.data} />;
case 'error': return <Err msg={state.error.message} />;
default: { const _: never = state; return _; }
}
}Revisions (0)
No revisions yet.