DEV Community

Mikey Stengel
Mikey Stengel

Posted on • Updated on

State machine advent: Statically type state machines with TypeScript (7/24)

In the last couple of days, we've seen how to define and invoke a state machine in React. Above all, for our application to work correctly, we must define our state machines flawlessly.

As state architecture grows, refactoring state nodes by adding new ones or moving them around will get increasingly difficult within the JSON machine definition.

By strictly typing state machines, we can ensure that the machine includes all the state nodes and events that we have defined in TypeScript.

The first thing we do is to define our state schema and all possible events.

interface LightSwitchStateSchema {
  states: {
    inactive: {};
    active: {};

type LightSwitchEvent = { type: 'TOGGLE' };

After having defined our state schema and event type, we can pass the types to the Machine function when creating our machine in XState. Do not worry about the first type argument any for now as we'll cover it in detail in a few days from now.

const lightSwitchMachine = Machine<any, LightSwitchStateSchema, LightSwitchEvent> ({
  id: 'lightSwitch',
  initial: 'inactive',
  states: {
    inactive: {
      on: {
        TOGGLE: 'active'
    active: {
      on: {
        TOGGLE: 'inactive'

Whenever we forget to define a state node or move it into an invalid position within our JSON, TypeScript will now rightfully scream at us. 🎉

If we had two distinct events instead of reusing our toggle event, our event type could look like this.

type LightSwitchEvent =
  | { type: 'ACTIVATE' }
  | { type: 'DEACTIVATE' };

Using TypeScript with state machines can reduce so many bugs in our apps. As a result, when we introduce more complex machines in the series, I'll make sure to always include how to type them as well.

Tomorrow we'll take a critical look at state machines and the one problem they can't solve on their own.

About this series

Throughout the first 24 days of December, I'll publish a small blog post each day teaching you about the ins and outs of state machines and statecharts.

The first couple of days will be spent on the fundamentals before we'll progress to more advanced concepts.

Discussion (0)