diff --git a/.changeset/nice-spiders-perform.md b/.changeset/nice-spiders-perform.md new file mode 100644 index 0000000000..0c4a2e09eb --- /dev/null +++ b/.changeset/nice-spiders-perform.md @@ -0,0 +1,21 @@ +--- +'@xstate/store': patch +--- + +The `context` type for `createStoreWithProducer(producer, context, transitions)` will now be properly inferred. + +```ts +const store = createStoreWithProducer( + produce, + { + count: 0 + }, + { + // ... + } +); + +store.getSnapshot().context; +// BEFORE: StoreContext +// NOW: { count: number } +``` diff --git a/packages/xstate-store/src/store.ts b/packages/xstate-store/src/store.ts index 96d701379f..d059a4e770 100644 --- a/packages/xstate-store/src/store.ts +++ b/packages/xstate-store/src/store.ts @@ -187,10 +187,10 @@ export function createStoreWithProducer< TContext extends StoreContext, TEventPayloadMap extends EventPayloadMap >( - producer: ( + producer: NoInfer<( context: TContext, recipe: (context: TContext) => void - ) => TContext, + ) => TContext>, initialContext: TContext, transitions: { [K in keyof TEventPayloadMap & string]: ( diff --git a/packages/xstate-store/test/store.test.ts b/packages/xstate-store/test/store.test.ts index b3fe3fb8f6..c595d70a47 100644 --- a/packages/xstate-store/test/store.test.ts +++ b/packages/xstate-store/test/store.test.ts @@ -97,7 +97,7 @@ it('updates state from sent events', () => { expect(store.getSnapshot().context).toEqual({ count: 0 }); }); -it('works with immer', () => { +it('createStoreWithProducer(…) works with an immer producer', () => { const store = createStoreWithProducer( produce, { @@ -120,6 +120,22 @@ it('works with immer', () => { expect(store.getInitialSnapshot().context).toEqual({ count: 0 }); }); +it('createStoreWithProducer(…) infers the context type properly with a producer', () => { + const store = createStoreWithProducer( + produce, + { + count: 0 + }, + { + inc: (ctx, ev: { by: number }) => { + ctx.count += ev.by; + } + } + ); + + store.getSnapshot().context satisfies { count: number }; +}); + it('can be observed', () => { const store = createStore( {