Skip to main content
🟦 TypeScript Projects

What you're building

A generic, typed finite-state machine (FSM) β€” the backbone of traffic lights, game logic, order management, and UI flows. Your FSM will enforce that only valid transitions are accepted, returning an error string when an invalid one is attempted.

Requirements

  • Define StateMachine<S extends string, E extends string> β€” a class parameterised over a union of state names and a union of event names.
  • Constructor accepts:
    • initial: S β€” the starting state
    • transitions: Array<{ from: S; event: E; to: S }>
  • getState(): S β€” returns the current state.
  • send(event: E): { ok: true; state: S } | { ok: false; error: string }
    • If a matching transition exists for (currentState, event), move to to and return { ok: true, state: to }.
    • Otherwise return { ok: false, error: "Invalid transition" }.

Stretch goals

  • Add a onEnter callback per state, fired whenever that state is entered.
  • Support guard predicates on transitions.

What this proves

You understand generics, discriminated unions, and how to model domain rules as data β€” all marquee TypeScript skills on any engineering job description.

⚑ 50 XP
solution.tsTranspiled & run in your browser
Loading editor…
Tests4 to pass
starts in initial state
valid transition advances state
invalid transition returns error
full cycle red β†’ green β†’ yellow β†’ red

Run your code to check these.