Model state with discriminated unions
Make impossible UI combinations harder to represent.
Avoid independent booleans
Separate isLoading, hasError, and hasData flags can all become true at once unless every update is coordinated. A discriminated union represents one state at a time. Keep the payload attached to the state that owns it, such as rows on ready and a message on error.
Make missing cases visible
A switch on the discriminator can render each state. A never check in the default branch asks TypeScript to flag a newly added state that the view does not handle. This is compile-time help; validate external JSON before treating it as the union.
type State = { kind: 'loading' } | { kind: 'ready'; rows: Row[] } | { kind: 'error'; message: string };
function unreachable(value: never): never { throw new Error('Unexpected state'); }
Trace transitions
Write down which event moves idle to loading, loading to ready, and loading to error. Decide what a retry does and whether stale rows remain visible. Test the transitions rather than only snapshots of one state; many UI bugs happen when requests overlap.
Check your understanding
Does a TypeScript union validate JSON received from a server?
Show explanation
No. The union checks code at compile time; untrusted runtime values still need validation.
You can read for free. Create an account to save your progress.
← Previous lesson: Make forms understandable to everyone Next lesson: Design a resilient search flow →Put this lesson into practice
A practice activity at this level in the same module.
Try: Make a custom list keyboard accessibleFurther reading
Primary references for this module. Check the current version when behavior or framework guidance may have changed.