Xstate: Type inference for initial

Created on 18 Jan 2019  路  5Comments  路  Source: davidkpiano/xstate

Bug or feature request?

Bug

Description:

Typescript doesn't know that initial value is fine

(Bug) Expected result:

Types should pass

(Bug) Actual result:

 Type 'string' is not assignable to type '"stopped" | "playing"'

(Bug) Potential fix:

Temporary Workaround in the following example is to change:

    initial: "stopped",

to:

    initial: "stopped" as "stopped",

Not sure how to fix it at the source

Link to reproduction or proof-of-concept:

Cloned the repo locally, built, and npm-linked. Then did the following:

import { Machine } from 'xstate';

interface Schema {
  states: {
    stopped: {};
    playing: {};
  };
}

type Event =
  | { type: 'STOP' }
  | { type: 'PLAY' };

interface Context {
  elapsed: number;
}

const Chart = {
    id: 'controller',
    initial: "stopped",
    context: {
        elapsed: 0
    },
    states: {
        stopped : {
            on: {
                PLAY: "playing" 
            }
        },
        playing : {
            on: {
                STOP: "stopped" 
            }
        },
    }
}

const ControllerMachine = Machine<Context, Schema, Event>(Chart);
documentation invalid

Most helpful comment

Until the machine config is inside the Machine(...) function, TS can't infer that the initial property is a key of the Schema. It just assumes it's a plain JS object.

This should solve your issue:

const Chart: MachineConfig<Context, Schema, Event> = {
  id: 'controller',
  initial: 'stopped',
  // ...
}

All 5 comments

Until the machine config is inside the Machine(...) function, TS can't infer that the initial property is a key of the Schema. It just assumes it's a plain JS object.

This should solve your issue:

const Chart: MachineConfig<Context, Schema, Event> = {
  id: 'controller',
  initial: 'stopped',
  // ...
}

Reopening this so I can add it to the docs.

Hey @davidkpiano , I'm having the same issues like @dakom but in my case with child states. I've tried your solution using MachineConfig with same results. I've just used the workaround provided (initial: 'blah' as 'blah') and it works for now.

@ccontreras could u prepare a repro case?

Closing this for now. @ccontreras Please try with xstate@next and prepare a repro case if this is still occurring.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mattiamanzati picture mattiamanzati  路  3Comments

hnordt picture hnordt  路  3Comments

greggman picture greggman  路  3Comments

kurtmilam picture kurtmilam  路  3Comments

3plusalpha picture 3plusalpha  路  3Comments