Skip to content
jshacks.dev
TypeScript

Model states with a discriminated union

Give each state its own object type with a literal status field, so success carries data and error carries a message and the compiler enforces it.

1 min read
Summarize in AI

A request is idle, loading, done or failed, and only one of those has data. One interface with optional data and error lets impossible combinations exist. A union does not.

state.tsTypeScript
type FetchState =
  | { status: 'idle' }
  | { status: 'loading' }
  | { status: 'success'; data: string }
  | { status: 'error'; message: string };

function render(state: FetchState): string {
  switch (state.status) {
    case 'idle':
      return 'waiting';
    case 'loading':
      return 'loading...';
    case 'success':
      return state.data;
    case 'error':
      return `failed: ${state.message}`;
  }
}

console.log(render({ status: 'success', data: 'hello' }));
console.log(render({ status: 'error', message: 'timeout' }));
Text
hello
failed: timeout

The shared status field is the discriminant. Checking it in a switch narrows state to the one member with that literal, so state.data exists only in the success case. Writing { status: 'loading', data: 'x' } is an error, because that member has no data. See discriminated unions.

With strict on, the function needs no default: every case returns, so the compiler knows the end is unreachable. Add a member and render stops compiling until you handle it, which is the point of exhaustiveness checking.

Share

More snippets

TypeScript

Make every property required with Required

Required of T removes the question mark from every property, which types a config object after its defaults have been filled in. TypeScript 5 and earlier.

1 min read
TypeScript

Declare types for an untyped module

Write a small .d.ts file with declare module so an untyped package gets real function signatures, instead of an implicit any error. TypeScript 5.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.