Skip to content
jshacks.dev
TypeScript

Type a state machine with discriminated states

Model each state of a machine as a union member with its own fields, so impossible combinations cannot be written. Works in TypeScript 5.

1 min read
Summarize in AI

A request with loading, data and error booleans can be loaded and failed at once. A union with one member per state cannot.

request.tsTypeScript
type Job =
  | { status: 'idle' }
  | { status: 'loading'; startedAt: number }
  | { status: 'success'; data: string[] }
  | { status: 'error'; message: string };

function describe(request: Job): string {
  switch (request.status) {
    case 'idle':
      return 'waiting';
    case 'loading':
      return `loading since ${request.startedAt}`;
    case 'success':
      return `${request.data.length} items`;
    case 'error':
      return `failed: ${request.message}`;
  }
}

console.log(describe({ status: 'success', data: ['a', 'b'] }));
console.log(describe({ status: 'error', message: 'timeout' }));
Text
2 items
failed: timeout

data exists only on the success state, so reading request.data anywhere else is a compile error, and an error object cannot carry a data array by accident. The pattern is discriminated unions with status as the tag.

Transitions are not checked by this type: nothing stops code from going from idle straight to success. If the order matters, write a transition(from, event) function with its own union of events, or use a state machine library.

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.