xstate icon indicating copy to clipboard operation
xstate copied to clipboard

Bug: [TypeScript] Unknown action when using `enqueue()` and referencing an action defined with `enqueueActions`

Open offirgolan opened this issue 1 year ago • 9 comments

XState version

XState version 5

Description

Typescript errors when calling an action via enqueue when the action being called is defined with enqueueActions.

setup({
  actions: {
    foo: enqueueActions(({ enqueue }) => {
      enqueue({ type: "bar" }); // TS ERROR
    }),
    bar: enqueueActions(({ enqueue }) => {
      enqueue.raise({ type: "submit" });
    }),
  },
})

Expected result

Typescript should not error when calling enqueue({ type: "bar" });

Actual result

Object literal may only specify known properties, and 'type' does not exist in type

Reproduction

https://codesandbox.io/p/devbox/currying-darkness-nvv5vh

Additional context

No response

offirgolan avatar Apr 01 '24 00:04 offirgolan

This is a current limitation that we are facing. TS can't infer this situation correctly: TS playground

Andarist avatar Apr 01 '24 06:04 Andarist

Can a type assertion be used as a workaround? I'm not sure what it'd be.

boneskull avatar Apr 02 '24 20:04 boneskull

@Andarist I found another TS error: TS Playground

setup({
  actions: {
    bar: enqueueActions(({ check }) => {
      check(stateIn('a'));
    }),
  },
}).createMachine({
  states: {
    a: {},
    b: {}
  }
});

+1 to @boneskull, if there is a TS limitation are there utility types that can be exposed to help mitigate the issue via type assertions?

offirgolan avatar Apr 05 '24 00:04 offirgolan

FWIW Using createMachine with the deprecated second argument instead of setup and defining types.actions and types.guards works.

Because of these TS limitations in setup, should I switch back to using createMachine?

Edit:

Another alternative is to add types.actions and types.guards to setup.

offirgolan avatar Apr 05 '24 17:04 offirgolan

Any updates?

andrecrimb avatar May 24 '24 14:05 andrecrimb

For now, just // @ts-ignore this - the action will work, we're just running into a TypeScript limitation, as previously mentioned.

davidkpiano avatar Jun 05 '24 00:06 davidkpiano

For now, just // @ts-ignore this

// @ts-expect-error so it'll become an error when (if?) the types work correctly 😁

with-heart avatar Jun 05 '24 02:06 with-heart

Just a comment that attempting to suppress the error with // @ts-expect-error did not work for me, because it breaks the Snapshot matches function. The possible states resolve to never. As soon as I moved the enqueueActions from my setup to be an inline action the states started resolving properly again.

UberMouse avatar Jul 30 '24 00:07 UberMouse