fn
createMachine
testedCreate a type-safe synchronous finite state machine with context
Example
ts
const machine = createMachine({
initial: 'idle',
context: { retries: 0 },
states: {
idle: {
on: { START: 'running' },
},
running: {
on: {
FAIL: {
target: 'idle',
guard: (ctx) => ctx.retries < 3,
action: (ctx) => { ctx.retries++; },
},
STOP: 'idle',
},
},
},
});
machine.send('START'); // 'running'Signatures
ts
export function createMachine<
const States extends Record<string, SyncStateNodeConfig<Context>>,
Context,
>(config: {
initial: NoInfer<ExtractStates<States>>;
context: Context;
states: States;
}): StateMachine<ExtractStates<States>, ExtractEvents<States>, Context>;ts
export function createMachine<
const States extends Record<string, SyncStateNodeConfig<undefined>>,
>(config: {
initial: NoInfer<ExtractStates<States>>;
states: States;
}): StateMachine<ExtractStates<States>, ExtractEvents<States>, undefined>;Parameters
| Parameter | Type | Description |
|---|---|---|
config | { initial: string; context?: unknown; // Overload-implementation signature: the typed overloads above expose the real // per-context API; `any` here accepts every concrete `SyncStateNodeConfig<C>` // (contravariant in `C`, so `unknown` would reject them). states: Record<string, SyncStateNodeConfig<any>>; } | — |
Returns
StateMachine| Property | Type | Description |
|---|---|---|
send | (event: string) => string | Send an event to the machine, potentially causing a state transition |
can | (event: string) => boolean | Check if an event can trigger a transition from the current state |
currentState | States | — |
states | Record<string, NodeConfig> | — |
context | Context | Machine context |
current | string | Current state of the machine |
matches | (state: string) => boolean | Check if the machine is in a specific state |