Most screens that load data start with three variables: isLoading, error and data. Three independent variables allow eight combinations, and only four of them make sense. The other four are bugs waiting for the right timing: a spinner over stale data, an error message next to a success view.

A discriminated union removes the impossible combinations at compile time.

The shape

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

Each member has the same status field with a different literal value. That shared field is the discriminant. data exists only on the success member and message only on the error member, so there is no way to build a value that is loading and also has an error.

Narrowing

When you check the discriminant, TypeScript narrows the type inside that branch:

function Orders({ state }: { state: Loadable<Order[]> }) {
  switch (state.status) {
    case 'idle':
      return null;
    case 'loading':
      return <Spinner />;
    case 'error':
      return <ErrorNote text={state.message} />;
    case 'success':
      return <OrderList orders={state.data} />;
  }
}

Inside the success branch state.data is an Order[], not Order[] | undefined. There is no optional chaining and no non-null assertion, because the type already proves the data is there.

The same union works in Angular: keep it in a signal and use @switch in the template.

Let the compiler find the missing case

The real payoff comes when the union grows. Say you add { status: 'empty' }. Every switch in the codebase that handles Loadable should now handle the new case. Add an exhaustiveness check and the compiler lists them for you:

function assertNever(value: never): never {
  throw new Error(`Unhandled case: ${JSON.stringify(value)}`);
}

// in the switch
default:
  return assertNever(state);

If every case is handled, state in the default branch has type never and the code compiles. Add a member without handling it and the call fails to type-check, pointing at the exact place to fix.

Beyond loading states

The pattern fits anything with distinct modes:

  • a form step: 'editing' | 'validating' | 'submitted', each with its own fields
  • a payment: 'card' with a last-four, 'transfer' with a reference number
  • API responses that differ by type

A useful test: if two fields are only meaningful together, or one is only meaningful when another has a certain value, they belong inside a union member rather than side by side as optionals.

Two habits that keep it clean

Create states through small functions (loading(), success(data)) rather than writing object literals everywhere; a typo in a status string becomes impossible. And resist adding an optional field "just for this one case". The moment a member gets an optional field, you are back to checking for undefined, which is the problem the union was solving.