States
What are States?
Section titled “What are States?”In Matchina, keyed object states are elegant strongly-typed building blocks that enable powerful type inference and pattern matching.
Keyed State Values
Section titled “Keyed State Values”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;}
Factory States
Section titled “Factory States”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
Using States
Section titled “Using States”Defining States
Section titled “Defining States”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
State Factory Types
Section titled “State Factory Types”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:
-
Factory Methods: Create state instances with proper typing
const stoppedState = states.Stopped(0);const tickingState = states.Ticking(42); -
Type Guards: Check state types safely
if (state.is("Ticking")) {// TypeScript knows state.data has elapsed and atconsole.log(state.data.at);} -
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)`,});
Related Concepts
Section titled “Related Concepts”To fully understand and use states in Matchina, explore these related topics:
- Matchbox Factories - The foundation of Matchina’s type-safe state system
- Factory Machines - How states are used in complete state machines
- Type Safety - Understanding type inference and guards
Next Steps
Section titled “Next Steps”Now that you understand states, you might want to:
- Learn about Factory Machines to use states in a complete system
- Explore Lifecycle Hooks to react to state changes
- Study Effects to manage side effects in your state machines
- Try Promise Machines for handling async operations