statelyai / xstate

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

[core] Strongly-typed state value #5006

Closed davidkpiano closed 3 months ago

davidkpiano commented 3 months ago

The state value typings for setup state machine actors (setup({}).createMachine({ ... })) have been improved to represent the actual expected state values.

const machine = setup({}).createMachine({
  initial: 'green',
  states: {
    green: {},
    yellow: {},
    red: {
      initial: 'walk',
      states: {
        walk: {},
        wait: {},
        stop: {}
      }
    },
    emergency: {
      type: 'parallel',
      states: {
        main: {
          initial: 'blinking',
          states: {
            blinking: {}
          }
        },
        cross: {
          initial: 'blinking',
          states: {
            blinking: {}
          }
        }
      }
    }
  }
});

const actor = createActor(machine).start();

const stateValue = actor.getSnapshot().value;

if (stateValue === 'green') {
  // ...
} else if (stateValue === 'yellow') {
  // ...
} else if ('red' in stateValue) {
  stateValue;
  // {
  //   red: "walk" | "wait" | "stop";
  // }
} else {
  stateValue;
  // {
  //   emergency: {
  //     main: "blinking";
  //     cross: "blinking";
  //   };
  // }
}
changeset-bot[bot] commented 3 months ago

🦋 Changeset detected

Latest commit: d7e92243384804ccfea1c56db9c54ce702ed856b

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package | Name | Type | | ------ | ----- | | xstate | Minor |

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

davidkpiano commented 3 months ago

@Andarist Ready for review