statelyai / xstate

Actor-based state management & orchestration for complex app logic.
https://stately.ai/docs
MIT License
26.87k stars 1.23k forks source link

Typescript helpers #304

Closed dakom closed 5 years ago

dakom commented 5 years ago

Bug or feature request?

feature

Description:

Assuming that states and events are predefined by enums, can we have Typescript helpers to wrap around the interpreter, so that we can check send() (and other properties/functions) against those enums?

(Feature) Potential implementation:

Maybe it's a wrapper around interpret... e.g. interpret<STATE, EVENT>(machine)

This is not a breaking change and could gradually support more and more optional type-checking features (e.g. after send(), maybe each state's ownEvents could be Partial<EVENT>, etc.)

Link to reproduction or proof-of-concept:

Here's a proof-of-concept of manually supplying the enums. I didn't attempt any work on xstate or interpret itself:

https://codesandbox.io/s/x9rz1qq85z

dakom commented 5 years ago

I see that there is already some type information there: https://github.com/davidkpiano/xstate/blob/ad162934fe769aa3920e684ee7789ad9034acd61/src/interpreter.ts#L716

Though I'm not sure how these relate to say the string values of state and event (i.e. what we pass to send() and what we get from the current state.value)

davidkpiano commented 5 years ago

This will work as expected:

screen shot 2019-01-17 at 4 29 09 pm

It recently went in thanks to this PR: https://github.com/davidkpiano/xstate/pull/303 and will be out in the next release. 👍

dakom commented 5 years ago

Wow, that's wonderful - so much better than the hacky enum idea I was toying with.

Can't wait! :D

dakom commented 5 years ago

Fwiw I think defining statecharts using the enums as in the example still has value since it allows catching mistakes in the config itself at runtime, and they can also be more easily passed to non-statechart functions without going through a complex typescript dance (e.g. some sort of "extends TEvent that was derived from the interpreter")

Not really an issue to impact the library itself, but might be worth noting somewhere as an approach to more pleasant ergonomics.

dakom commented 5 years ago

Ohhh...... whups.... didn't see this page in the docs: https://xstate.js.org/docs/guides/typescript.html#using-typescript

And my newbie states/events don't approach real-world possibilities. Cool - will follow the doc :D