CodingNeed.
Mid · Language concepts

Model API States with Unions

Model idle, loading, success, and error states with a discriminated union. Prevent impossible combinations and exhaustively render each state.

Examples

Compare approaches

Baseline approach

Begin by explaining the core mechanism, stating assumptions, and walking through one concrete example.

Time: Depends on design · Space: Depends on design

type State<T> =
  | { status: "idle" }
  | { status: "loading" }
  | { status: "success"; data: T }
  | { status: "error"; message: string };
Strong answer

A discriminant makes available fields depend on the state. An exhaustive switch with a never check catches newly added variants.

Time: Discuss operation costs · Space: Discuss retained state

type State<T> =
  | { status: "idle" }
  | { status: "loading" }
  | { status: "success"; data: T }
  | { status: "error"; message: string };

Common traps

  • Optional data and error fields permit inconsistent states.
  • State assumptions and justify trade-offs rather than memorizing a single answer.
Practise in the workspace →

Essential cookies keep your account signed in. Optional analytics is not configured on this site. Your choice does not affect access to lessons.

Read the Privacy Policy. You can change this choice in the footer.