Skip to content

Commit

Permalink
[@xstate/store] Fix createStoreWithProducer(…) types (#4890)
Browse files Browse the repository at this point in the history
* Fix createStoreWithProducer() types

* Changeset

* Update packages/xstate-store/src/store.ts

Co-authored-by: Mateusz Burzyński <[email protected]>

---------

Co-authored-by: Mateusz Burzyński <[email protected]>
  • Loading branch information
davidkpiano and Andarist authored May 12, 2024
1 parent 63ac3ad commit 6d92b77
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 3 deletions.
21 changes: 21 additions & 0 deletions .changeset/nice-spiders-perform.md
Original file line number Diff line number Diff line change
@@ -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 }
```
4 changes: 2 additions & 2 deletions packages/xstate-store/src/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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]: (
Expand Down
18 changes: 17 additions & 1 deletion packages/xstate-store/test/store.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
{
Expand All @@ -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(
{
Expand Down

0 comments on commit 6d92b77

Please sign in to comment.