← All Exercises

Typed Finite State Machine

advancedtypescript~15min

Background

Explicit state machines prevent impossible transitions such as showing success before a request starts. Typing states and events as unions, and the table as a record, keeps the transition graph reviewable and exhaustively editable.

Problem

Implement StateMachine<S, E> with a transition table typed as Record<S, Partial<Record<E, S>>>. The machine records its initial state, exposes state, and send(event) moves to the next state or throws INVALID:EVENT:STATE. Drive a request lifecycle (idle, loading, success, error) from a JSON event list and report visited states plus any error.

Input

A JSON object with initial state and events, where events are FETCH, SUCCESS, FAIL, or RESET.

Output

A JSON object with states (the initial state followed by every successful transition) and error (null or the rejection message).

Sample tests

Sample 1

Input: {"initial":"idle","events":["FETCH","SUCCESS","RESET"]}
Expected: {"states":["idle","loading","success","idle"],"error":null}

Sample 2

Input: {"initial":"idle","events":["SUCCESS"]}
Expected: {"states":["idle"],"error":"INVALID:SUCCESS:idle"}

Sample 3

Input: {"initial":"idle","events":["FETCH","FAIL","RESET"]}
Expected: {"states":["idle","loading","error","idle"],"error":null}

Your solution

Learning objective

Model legal transitions with generics and Record types, and enforce state changes at runtime.