Typed State Machine With Transition Guards
Model finite states with typed events, guarded transitions, transition history and clear errors for illegal or rejected moves.
Code
export interface Transition<State extends string, Event extends string, Context> {
from: State;
event: Event;
to: State;
guard?: (context: Context, event: Event) => boolean;
}
export interface StateMachineOptions<State extends string, Event extends string, Context> {
context: Context;
onTransition?: (next: State, previous: State, event: Event) => void;
}
export class StateMachine<State extends string, Event extends string, Context = undefined> {
private current: State;
private readonly transitions: ReadonlyArray<Transition<State, Event, Context>>;
private readonly context: Context;
private readonly onTransition?: (next: State, previous: State, event: Event) => void;
private readonly history: State[] = [];
constructor(
initial: State,
transitions: ReadonlyArray<Transition<State, Event, Context>>,
options: StateMachineOptions<State, Event, Context>,
) {
if (!Array.isArray(transitions)) throw new TypeError("transitions must be an array");
for (const transition of transitions) {
if (!transition.from || !transition.event || !transition.to) {
throw new TypeError("transition requires from, event and to");
}
if (transition.guard !== undefined && typeof transition.guard !== "function") {
throw new TypeError("guard must be a function");
}
}
this.current = initial;
this.transitions = [...transitions];
this.context = options.context;
this.onTransition = options.onTransition;
}
get state(): State {
return this.current;
}
get previousStates(): readonly State[] {
return [...this.history];
}
can(event: Event): boolean {
return this.transitions.some((transition) =>
transition.from === this.current &&
transition.event === event &&
(!transition.guard || transition.guard(this.context, event)));
}
send(event: Event): State {
const transition = this.transitions.find((candidate) =>
candidate.from === this.current && candidate.event === event);
if (!transition) {
throw new Error("no transition from " + this.current + " on " + event);
}
if (transition.guard && !transition.guard(this.context, event)) {
throw new Error("guard rejected " + this.current + " -> " + transition.to + " on " + event);
}
const previous = this.current;
this.current = transition.to;
this.history.push(this.current);
this.onTransition?.(this.current, previous, event);
return this.current;
}
}How it works
StateMachine is the single class; Transition and StateMachineOptions are its typed inputs.
Iteration happens inside for (const transition of transitions) — everything outside it runs once. Invalid states are rejected up front: it throws TypeError and Error instead of continuing with bad data.
The result is a fresh construction, so callers can keep their originals.
What to watch for
- The guard
!transition.from || !transition.event || !transition.toshort-circuits the flow with an earlythrowwhen its condition holds.
Putting it to use
StateMachine is what another module would consume; nothing else here is load-bearing for callers.
Core lines
return this.transitions.some((transition) =>
transition.from === this.current &&
transition.event === event &&
(!transition.guard || transition.guard(this.context, event)));
throw new Error("guard rejected " + this.current + " -> " + transition.to + " on " + event);
private readonly onTransition?: (next: State, previous: State, event: Event) => void;
Interactive Tools for This Topic
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- Does `StateMachine` modify its input?
- No. The code builds and returns a new value and leaves the arguments untouched, so it is safe to call on shared or frozen data structures.
- What happens on invalid input?
- Validation comes first — `TypeError` and `Error` marks the failure at `!transition.from || !transition.event || !transition.to`, before any partial work happens.
- Will the snippet run without installing packages?
- Yes, it runs as-is — nothing outside the built-in APIs is referenced. Every import resolves inside the standard library — ` + this.current + `.
Report a problem with this exampleOpens a pre-filled issue on GitHub.