Skip to content

Bug: spawn and spawnChild has type error when using setup() #5356

@GrahLnn

Description

@GrahLnn

XState version

XState version 5

Description

When using setup({}) together with spawnChild in vscode, TypeScript produces a type error if an id is provided in the options.

import { createMachine, spawnChild, setup, assign } from 'xstate';

const childMachine = createMachine({});

setup({}).createMachine({
  entry: spawnChild(childMachine, {
    id: 'child', // Type 'string' is not assignable to type 'undefined'.(2322)
  }),
});

createMachine({
  entry: spawnChild(childMachine, {
    id: 'child', // this ok
  }),
});

setup({
  types: {
    context: {} as { childMachineRef?: any },
  },
}).createMachine({
  entry: assign({
    childMachineRef: ({ spawn }) => spawn(childMachine, { id: 'child' }),
    // No overload matches this call.
    // Overload 1 of 2, '(logic: never, ...[options]: never): ActorRefFromLogic<never>', gave the following error.
    //   Argument of type 'StateMachine<MachineContext, AnyEventObject, Record<string, AnyActorRef>, ProvidedActor, ParameterizedObject, ... 8 more ..., any>' is not assignable to parameter of type 'never'.
    // Overload 2 of 2, '(src: StateMachine<MachineContext, AnyEventObject, Record<string, AnyActorRef>, ProvidedActor, ParameterizedObject, ... 8 more ..., any>, options?: ({ ...; } & {}) | undefined): ActorRefFromLogic<...>', gave the following error.
    //   Type 'string' is not assignable to type 'undefined'.(2769)
  }),
});

createMachine({
  entry: assign({
    childMachineRef: ({ spawn }) => spawn(childMachine, { id: 'child' }), // ok
  }),
});

Expected result

expected no type error

Actual result

(alias) spawnChild<MachineContext, AnyEventObject, undefined, AnyEventObject, never>(src: AnyActorLogic, options?: (SpawnActionOptions<MachineContext, AnyEventObject, AnyEventObject, ProvidedActor> & {
    id?: never;
}) | undefined): ActionFunction<MachineContext, AnyEventObject, AnyEventObject, undefined, never, never, never, never, never>
import spawnChild

Reproduction

https://stackblitz.com/edit/github-96otcbfr?file=src%2Fmain.ts

Additional context

No response

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions