Dev Helpers

TypeScript / State machines

Create an initial state

Dev Helpers · March 28, 2026

An initial state object establishes which variants are available before the first event. Check how literal values are inferred when assigning it.

Worked example

type State =
  | { phase: "idle" }
  | { phase: "loading"; id: number }
  | { phase: "ready"; text: string }
  | { phase: "error"; reason: string };
console.log({ phase: "idle" } satisfies State);

Result

{ phase: 'idle' }

Implementation notes

Avoid widening a state tag to string when later logic depends on a closed union. A deliberate annotation can keep the state machine visible.

Try it yourself

Change the initial discriminant and inspect reducers that consume the state.

Open the TypeScript example →

Editorial date March 28, 2026 · Published December 6, 2026

Related articles

Reject fractional cent amounts

A numeric type cannot by itself guarantee whole cents. Validate integrality where money enters the typed part of the application.

Infer route names from a registry

A route registry can drive both lookup and allowed route names. Type the keys from the registry so a removed route cannot survive in a separate union.