#How Auto Type Narrowing?

1 messages · Page 1 of 1 (latest)

tranquil tangle
#

like the following demo machine

const demoMachine = setup({
  types: {
    context: {} as {
      num: number | null;
    },
  },
  actors: {
    load: fromPromise(
      async () => new Promise<{ num: number }>(() => ({ num: 1 })),
    ),
  },
}).createMachine({
  id: "demo",
  initial: "loading",
  context: {
    num: null,
  },
  states: {
    loading: {
      invoke: {
        src: "load",
        onDone: {
          target: "loaded",
          actions: assign({ num: ({ event }) => event.output.num }),
        },
      },
    },
    loaded: {
      always: {
        actions: ({ context:{num} }) => {
          // do somethin with num
          // num actually is a number, but the type system is number | null, how to narrow it?
        }
      },
    },
  },
});

At loaded state the num is alreday not null, is there anyway to correct the type? Maybe define context type for state

type StateContext = {state:"loading"; context: {num: null}} | {state: "loaded"|"otherState"; context:{num:number}}
carmine sparrow
#

This is becoming a more and more frequent request 😅 we call this "typestates", and it's something we're still figuring out how to support in XState.