Need help with xstate-codegen?
Click the “chat” button below for chat support from the developer who created it, or find similar developers for support.

About the developer

mattpocock
221 Stars 13 Forks MIT License 171 Commits 37 Opened issues

Description

A codegen tool for 100% TS type-safety in XState

Services available

!
?

Need anything else?

Contributors list

# 61,424
TypeScr...
GraphQL
tailwin...
reactjs
21 commits
# 105,337
React N...
C#
reactjs
c-sharp
8 commits
# 1,574
React
TypeScr...
Redux
CSS
4 commits
# 182,829
CSS
Clojure
xstate
state-m...
1 commit
# 165,533
HTML
Shell
Amazon ...
xstate
1 commit

Type Safe State Machines

xstate-codegen
gives you 100% type-safe usage of XState in Typescript. Try it out at this codesandbox!

You get type safety on:

  • Transition targets:
    on: {EVENT: 'deep.nested.state'}
  • Services
  • Guards
  • Activities
  • Actions
  • The
    initial
    attribute
  • state.matches('deep.nested.state')

This works by introspecting your machine in situ in your code. With this Thanos-level power, we can click our fingers and give you 100% type safety in your state machines.

Usage

CLI

xstate-codegen "src/**/**.machine.ts"

Inside code

Instead of importing

createMachine
or
Machine
from
xstate
, import them from
@xstate/compiled
:
import { createMachine } from '@xstate/compiled';

const machine = createMachine();

You must pass three type options to

createMachine/Machine
:
  1. The desired shape of your machine's context
  2. The list of events your machine accepts, typed in a discriminated union (
    type Event = { type: 'GO' } | { type: 'STOP' };
    )
  3. A string ID for your machine, unique to your project.

For instance:

import { Machine } from '@xstate/compiled';

interface Context {}

type Event = { type: 'DUMMY_TYPE' };

const machine = Machine({});

Usage with React

import { useMachine } from '@xstate/compiled/react';
import { machine } from './myMachine.machine'

const [state, dispatch] = useMachine(machine, { // all options in here will be type checked })

Usage with Interpret

import { interpret } from '@xstate/compiled';
import { machine } from './myMachine.machine'

const service = interpret(machine, { // all options in here will be type checked })

Options

Once

xstate-codegen "src/**/**.machine.ts" --once

By default, the CLI watches for changes in your files. Running

--once
runs the CLI only once.

Out Dir

xstate-codegen "src/**/**.machine.ts" --outDir="src"

By default, the CLI adds the required declaration files inside nodemodules at `nodemodules/@xstate/compiled`. This writes the declaration files to a specified directory.

Note, this only writes the declaration files to the directory. The

.js
files still get written to
node_modules/@xstate/compiled
.

We use cookies. If you continue to browse the site, you agree to the use of cookies. For more information on our use of cookies please see our Privacy Policy.