Skip to content

Typed Input Payloads

By default, handle() accepts any extra arguments, and handlers receive them as unknown. Under those defaults the compiler accepts a missing payload, a wrong payload, a misspelled input name, and a handler key outside the machine’s inputs. Each one fails at runtime.

An input payload map moves the mistakes to compile time. You declare each input’s arguments once, as a tuple. TypeScript infers the handler parameters from the declaration and checks every handle() call against it.

The map is a type-checking guardrail that the engine never reads: the runtime behavior does not change, and the untyped forms keep working exactly as before.

The map is a type that pairs each input name with an argument tuple. An empty tuple declares a payload-free input.

import { createFsm } from "machina";

type TrafficLightInputs = {
    timeout: [];
    emergency: [event: { severity: number }];
};

const light = createFsm<TrafficLightInputs>()({
    id: "traffic-light",
    initialState: "green",
    context: { minSeverity: 3 },
    states: {
        green: {
            timeout: "yellow",
            // `event` is inferred as { severity: number } — no annotation, no cast
            emergency({ ctx }, event) {
                if (event.severity < ctx.minSeverity) {
                    return;
                }
                return "red";
            },
        },
        yellow: { timeout: "red" },
        red: {},
    },
});

light.handle("emergency", { severity: 5 }); // ok
light.handle("emergency"); // error: payload missing
light.handle("emergency", { severity: "high" }); // error: severity must be a number
light.handle("emergencyy", { severity: 5 }); // error: unknown input

Note the call form: createFsm<TrafficLightInputs>()({...}). The first call takes the map and nothing else. The function it returns takes the config and infers everything else from it, exactly as the direct form does.

The split exists because TypeScript has no partial type-argument inference. A map supplied alongside the config would turn off inference for the states object, and a typo in a transition target would no longer be a compile error.

For a BehavioralFsm, the map is the second type argument of the existing curried form:

const connectionFsm = createBehavioralFsm<Connection, ConnectionInputs>()({ ... });

The same slot also takes a vocabulary bag, an object type with an inputs member, an events member, or both. The events member declares the payloads of the custom events the FSM emits, which the events guide covers:

const light = createFsm<{ inputs: TrafficLightInputs; events: TrafficLightEvents }>()({ ... });

A bare input map and a bag with an inputs member mean the same thing for inputs. An input map’s values are all tuples, and a bag’s members are object maps. TypeScript uses that difference to tell the two forms apart.

The map declares the complete list of inputs the machine handles, and TypeScript holds the config to that list. Every handler key in every state must be a key of the map. With TrafficLightInputs above, a state containing timout: "yellow" fails to compile, and the error anchors on that state. The untyped path cannot catch the mistake, because its index signature (the type that lets states accept any input name) accepts any key.

The same rule covers bubbles. A bubbles entry declares an input the FSM fires at itself, expecting a parent to handle it. The map is the complete set of inputs the machine can fire, so an entry outside the map is rejected at the declaration.

Many applications already describe their inbound messages as a discriminated union: one object type per message, with a shared field (here type) that identifies which message you have. InputMapFromUnion builds the map from that union, and you write the union once:

import type { InputMapFromUnion } from "machina";

type TrafficLightEvent =
    { type: "emergency"; severity: number } | { type: "pedestrianRequest"; crossingId: string };

type TrafficLightInputs = InputMapFromUnion<TrafficLightEvent>;
// => { emergency:         [event: { type: "emergency"; severity: number }];
//      pedestrianRequest: [event: { type: "pedestrianRequest"; crossingId: string }] }

Each handler receives the whole event as its payload, with the discriminant (type) included. Dispatch passes the event straight through: light.handle("emergency", event).

Your application receives these events from the outside: socket callbacks, timer expirations, clicks. You will want one function that hands any event to the machine, and the natural version reads the input name off the event:

// error: TypeScript cannot correlate `e.type` with `e`
const send = (e: TrafficLightEvent) => light.handle(e.type, e);

TypeScript rejects the one-liner because it checks e.type and e as two independent unions, and it cannot prove both came from the same union member. A literal input name compiles, a wrapper over one event type compiles, and so does a forwarder that narrows with a switch. For the union forwarder, pick one of two patterns:

// Checked: each case narrows, so every call is fully verified.
const send = (e: TrafficLightEvent) => {
    switch (e.type) {
        case "emergency":
            return light.handle("emergency", e);
        case "pedestrianRequest":
            return light.handle("pedestrianRequest", e);
    }
};

// Shortcut: one cast, one comment. The payloads were already checked
// where the events were built.
const sendUnchecked = (e: TrafficLightEvent) => light.handle(e.type, e as never);

The switch gives full checking at the cost of one line per input. The cast gives one line total at the cost of trusting the event’s builder.

A typed parent’s handle() accepts only the keys of its own map. Mounting a _child does not add the child’s inputs automatically. When the parent should forward a child’s input, declare that input and its tuple in the parent’s map too. The complete-list rule applies to hierarchy unchanged: the parent’s map lists everything the parent accepts.

machina-test’s walkAll reads the map from your factory’s return type. For a typed FSM, the config requires one tuple-returning generator per payload-carrying input, and a forgotten or misspelled generator fails at compile time, before any walk runs. See typed payload generators.