Skip to content

States

In Matchina, keyed object states are elegant strongly-typed building blocks that enable powerful type inference and pattern matching.

KeyedState is the foundational state type in Matchina. It only has a key property, which is used to identify the state. From here, you can build more complex state types by adding more properties.

export interface KeyedState {
key: string;
}

Matchina provides defineStates to create a StateMatchboxFactory. These state factories create StateMatchbox instances as type-safe tagged unions.

This means each state:

  • Has a unique key (tag)
  • Can carry its own data payload
  • Supports pattern matching
  • Has built-in type guards

The primary way to define states is using the defineStates function. This creates a type-safe state factory:

const states = defineStates({
Stopped: (elapsed = 0) => ({ elapsed }),
Ticking: (elapsed = 0) => ({ elapsed, at: Date.now() }),
Suspended: (elapsed = 0) => ({ elapsed }),
});

Each key in the configuration becomes a state constructor that:

  • Infers parameter types automatically
  • Creates properly typed state instances
  • Provides type-safe access to state data

The defineStates function is a thin wrapper around matchboxFactory that sets the tag property to “key”. You can think of it as:

const states = matchboxFactory(config, "key");

This means states inherit all the powerful features of Matchboxes:

  1. Factory Methods: Create state instances with proper typing

    const stoppedState = states.Stopped(0);
    const tickingState = states.Ticking(42);
  2. Type Guards: Check state types safely

    if (state.is("Ticking")) {
    // TypeScript knows state.data has elapsed and at
    console.log(state.data.at);
    }
  3. Pattern Matching: Match against state variants exhaustively

    const getDisplay = (state) => state.match({
    Stopped: ({ elapsed }) => `${elapsed}s`,
    Ticking: ({ elapsed }) => `${elapsed}s...`,
    Suspended: ({ elapsed }) => `${elapsed}s (paused)`,
    });

To fully understand and use states in Matchina, explore these related topics:

Now that you understand states, you might want to:

  1. Learn about Factory Machines to use states in a complete system
  2. Explore Lifecycle Hooks to react to state changes
  3. Study Effects to manage side effects in your state machines
  4. Try Promise Machines for handling async operations