Skip to content
Published on
2 min read

Give each UI state one TypeScript shape

Authors
  • Ritenta
    Name
    Ritenta

An API-backed panel might store loading, error and items independently. Nothing stops it from being “loading” and “failed” at once, or from showing yesterday's items beneath a new error. A discriminated union makes the allowed phases explicit. TypeScript then narrows the data available in each branch. The TypeScript Handbook explains narrowing and exhaustive checks.

type PanelState<T> =
  | { status: 'idle' }
  | { status: 'loading' }
  | { status: 'ready'; items: T[] }
  | { status: 'failed'; message: string };

function renderLabel<T>(state: PanelState<T>): string {
  switch (state.status) {
    case 'idle': return 'Choose a topic';
    case 'loading': return 'Loading topics';
    case 'ready': return `${state.items.length} topics`;
    case 'failed': return state.message;
    default: {
      const unreachable: never = state;
      return unreachable;
    }
  }
}

The status field is the discriminant. In the ready branch, items exists; in the failed branch, message exists. If you add a refreshing phase and forget to update the switch, the never assignment flags the missing case during type checking. This guards your own code paths; it does not validate untrusted JSON from a server. Parse external responses at the boundary.

Keep the model honest

Decide whether an empty successful list is still ready or deserves a separate empty phase. Both are reasonable if the UI behavior is clear. Decide what happens when a refresh fails but old data remains: that may need a state with both retained items and a warning, rather than forcing every failure to erase the screen.

Try listing every state the user can actually see: initial, pending, empty, populated, stale and failed. Give each a clear rendering rule, then check that your type permits those states and rejects contradictory combinations. A useful type model makes product behavior easier to reason about, not just the compiler quieter.