Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type inference for initial #310

Closed
dakom opened this issue Jan 18, 2019 · 5 comments
Closed

Type inference for initial #310

dakom opened this issue Jan 18, 2019 · 5 comments

Comments

@dakom
Copy link
Contributor

dakom commented Jan 18, 2019

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);
@davidkpiano
Copy link
Member

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',
  // ...
}

@davidkpiano
Copy link
Member

Reopening this so I can add it to the docs.

@ccontreras
Copy link

ccontreras commented Aug 28, 2019

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.

@davidkpiano davidkpiano reopened this Aug 28, 2019
@Andarist
Copy link
Member

@ccontreras could u prepare a repro case?

@davidkpiano
Copy link
Member

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants