Typed State Machine Transitions

Model states and allowed transitions as types so invalid transitions are rejected by the compiler and the reducer stays exhaustive.

TypescriptResilience

Code

typescriptsnippet
25 lines
type State =
  | { value: "idle" }
  | { value: "loading"; startedAt: number }
  | { value: "ready"; data: string[] }
  | { value: "failed"; error: string };

type Event =
  | { type: "fetch" }
  | { type: "resolve"; data: string[] }
  | { type: "reject"; error: string }
  | { type: "reset" };

export function reduce(state: State, event: Event): State {
  switch (state.value) {
    case "idle":
      return event.type === "fetch" ? { value: "loading", startedAt: Date.now() } : state;
    case "loading":
      if (event.type === "resolve") return { value: "ready", data: event.data };
      if (event.type === "reject") return { value: "failed", error: event.error };
      return state;
    case "ready":
    case "failed":
      return event.type === "reset" ? { value: "idle" } : state;
  }
}

How it works

One exported function, reduce, maps every Event variant onto the State union.

The result is a fresh construction, so callers can keep their originals.

What to watch for

  • This is browser-side code — fetch will not resolve in Node.
  • The guard event.type === "resolve" short-circuits the flow with an early return when its condition holds.

Using it

Signature: export function reduce(state: State, event: Event)

reduce is what another module would consume; nothing else here is load-bearing for callers.

Key statements

return event.type === "fetch" ? { value: "loading", startedAt: Date.now() } : state;
if (event.type === "reject") return { value: "failed", error: event.error };
if (event.type === "resolve") return { value: "ready", data: event.data };

Interactive Tools for This Topic

FAQ

Does `reduce` modify its input?
The input survives unchanged; what you get back is a newly constructed value.
Do I need to install anything before running this?
No — every API used here ships with the language runtime, so there is nothing to install. The file defines `reduce` at load time.