Skip to the content

Lesson 107 of 296

Discriminated unions

What you will learn

  • What a discriminated union is
  • Modelling loading, success and error states
  • Handling every case with switch
  • Making impossible states impossible
On this page

The problem

A common way to store a request's state:

type RequestState = {
  isLoading: boolean;
  data?: User;
  error?: string;
};

This allows impossible combinations: isLoading: true and an error, or data and an error at the same time. The code must constantly guess which fields are valid. Bugs follow.

The solution: a discriminated union

Make each state a separate type, each with a shared property holding a different literal value. That property is called the discriminant (or tag).

type RequestState =
  | { status: "idle" }
  | { status: "loading" }
  | { status: "success"; data: User }
  | { status: "error"; error: string };

Now:

  • data only exists in the success state.
  • error only exists in the error state.
  • Impossible combinations cannot be created.

Handling each case

Checking the discriminant narrows to exactly one member:

function render(state: RequestState): string {
  switch (state.status) {
    case "idle":
      return "Press load";
    case "loading":
      return "Loading...";
    case "success":
      return `Hello ${state.data.name}`;     state.data exists here
    case "error":
      return `Error: ${state.error}`;        state.error exists here
  }
}

Trying to read state.data in the "error" case is a compile error.

Creating states

let state: RequestState = { status: "idle" };

async function load(id: number) {
  state = { status: "loading" };
  try {
    const data = await fetchUser(id);
    state = { status: "success", data };
  } catch (e) {
    state = { status: "error", error: e instanceof Error ? e.message : "Unknown error" };
  }
}

More examples

Shapes:

type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "rectangle"; width: number; height: number };

function area(shape: Shape): number {
  switch (shape.kind) {
    case "circle":
      return Math.PI * shape.radius ** 2;
    case "rectangle":
      return shape.width * shape.height;
  }
}

Payment results:

type PaymentResult =
  | { ok: true; transactionId: string }
  | { ok: false; reason: "declined" | "insufficient_funds" | "network" };

Events and actions (very common with useReducer and Redux, Part 12):

type CartAction =
  | { type: "add"; productId: string; qty: number }
  | { type: "remove"; productId: string }
  | { type: "clear" };

Why interviewers love this

"Model an API request state" is a direct task in your study plan. A discriminated union shows you can design types that prevent bugs, not just describe data. The phrase to remember: make impossible states impossible.

Common mistakes

  • Several optional booleans instead of one status.
  • A discriminant typed as string instead of literal values, which breaks narrowing.
  • Destructuring before checking the discriminant (const { data } = state loses the link).

How to say it in an interview

"A discriminated union is a union of object types that share a literal discriminant property, like status. Checking that property, usually in a switch, narrows to exactly one member, so data is only available in the success state and error only in the error state. Compared with optional fields and booleans, it makes impossible states unrepresentable. I use it for request states, reducer actions and results."

Key words

WordMeaning
Discriminated unionA union of objects with a shared literal tag property
Discriminant / tagThe property whose literal value identifies each member
Impossible stateA combination of values that should never happen

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.