Typescript and Extracting Compound States in Xstate5 #4697
Unanswered
emarksamica
asked this question in
Q&A
Replies: 1 comment 1 reply
-
@emarksamica I'm struggling with this sort of thing as well. The only suggestion I have is that you can write |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I'm in the process of upgrading some of our existing state machines from version 4 to version 5. In our existing state machines, we have machines defined like this, where some compound states are extracted from the main machine, declared as their own variable, and referenced within the machine:
I've converted one of our machines to use the setup().createMachine() pattern, where actors/actions/guards implementations are declared, along with events/context/input defined in types in order to take advantage of the new TypeScript support in xstate5. Simple cases like the one shown above seem to work fine, but I've found that under certain circumstances, a compound state that successfully passes type checking validation when defined inline within the machine will fail if the same compound state is declared in a const and referenced that way instead. It appears that it takes issue with actor invocations and actions called within state transitions.
src: Services.MY_SERVICE,
to this:
src: Services.MY_SERVICE as Services.MY_SERVICE,
to this:
Similarly to the issue with declaring the invocation src, the actions have to be reasserted as not being
string
and instead as itself:That said, even though these fixes should work, making these adjustments is beginning to feel like a code smell and I'm wondering if there might be a better approach to what we're doing here. Along with the above issues, we lose the advantages of being able to leverage auto-complete in vscode and get more insightful typechecking when working within our compound state.
I've also played around with establishing the type of the compound state as AnyStateNodeConfig, and while this fixes the actor/action issues and lets us take some advantage of auto-complete, it means we can't match on any of the child states within the compound state so the value of this approach is pretty questionable.
Is there any recommendation to how something like this should be approached? I believe some of our other xstate4 machines do this in order to have a reusable set of state nodes to be used across multiple machines, and before we tackle those I'd be curious if there's a better way to do this.
Beta Was this translation helpful? Give feedback.
All reactions