Sikau

TypeScript · Day 24 · about 40 min

Capstone: Typed state machine

Discriminated unions, generics and reducers together.

Everything, typed

Your final project: the state of a data request — idle, loading, loaded or failed — modelled as a discriminated union, changed by a typed reducer with typed actions. This exact pattern powers loading screens in real apps.

The model

type State<T> =
  | { status: "idle" }
  | { status: "loading" }
  | { status: "loaded"; data: T }
  | { status: "failed"; error: string };

type Action<T> =
  | { type: "start" }
  | { type: "success"; data: T }
  | { type: "failure"; error: string }
  | { type: "reset" };

The rest of this lesson

  • Actions as a union tooexplain
  • Rendering from a unionexplain
  • A request's lifeorder
  • Reduce an actionpredict
  • Build the reducerchallenge
  • Badge quizquiz
  • TypeScript complete!recap

Continue this lesson free — run real code in your browser

Continue with Google

See all 24 lessons of TypeScript