From 6d92b77704750498f669487da185eb005a080034 Mon Sep 17 00:00:00 2001 From: David Khourshid Date: Sun, 12 May 2024 18:59:53 -0400 Subject: [PATCH] =?UTF-8?q?[@xstate/store]=20Fix=20`createStoreWithProduce?= =?UTF-8?q?r(=E2=80=A6)`=20types=20(#4890)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Fix createStoreWithProducer() types * Changeset * Update packages/xstate-store/src/store.ts Co-authored-by: Mateusz Burzyński --------- Co-authored-by: Mateusz Burzyński --- .changeset/nice-spiders-perform.md | 21 +++++++++++++++++++++ packages/xstate-store/src/store.ts | 4 ++-- packages/xstate-store/test/store.test.ts | 18 +++++++++++++++++- 3 files changed, 40 insertions(+), 3 deletions(-) create mode 100644 .changeset/nice-spiders-perform.md 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( {