Skip to content

Commit

Permalink
Merge pull request #2632 from statelyai/davidkpiano/model-actions-fix
Browse files Browse the repository at this point in the history
[core] Allow any action if action creators are not specified in model
  • Loading branch information
davidkpiano committed Sep 14, 2021
2 parents ef70ce9 + f8cf5df commit cda1b9e
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 4 deletions.
20 changes: 20 additions & 0 deletions .changeset/slow-timers-nail.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
---
'xstate': patch
---

A regression was fixed where actions were being typed as `never` if events were specified in `createModel(...)` but not actions:

```ts
const model = createModel(
{},
{
events: {}
}
);

model.createMachine({
// These actions will cause TS to not compile
entry: 'someAction',
exit: { type: 'someObjectAction' }
});
```
8 changes: 5 additions & 3 deletions packages/core/src/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,11 @@ export function createModel<
TComputedEvent = 'events' extends keyof TFinalModelCreators
? UnionFromCreatorsReturnTypes<TFinalModelCreators['events']>
: never,
TComputedAction = 'actions' extends keyof TFinalModelCreators
? UnionFromCreatorsReturnTypes<TFinalModelCreators['actions']>
: never
TComputedAction = 'actions' extends keyof TModelCreators
? 'actions' extends keyof TFinalModelCreators
? UnionFromCreatorsReturnTypes<TFinalModelCreators['actions']>
: any
: any
>(
initialContext: TContext,
creators: TModelCreators
Expand Down
27 changes: 26 additions & 1 deletion packages/core/test/model.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -436,7 +436,14 @@ describe('createModel', () => {
});

it('should typecheck `createMachine` for model without creators', () => {
const toggleModel = createModel({ count: 0 });
const toggleModel = createModel(
{ count: 0 },
{
events: {
TOGGLE: () => ({})
}
}
);

toggleModel.createMachine({
id: 'machine',
Expand Down Expand Up @@ -519,6 +526,24 @@ describe('createModel', () => {
});
});

it('should allow any action if actions are not specified', () => {
const model = createModel(
{},
{
events: {}
}
);

model.createMachine({
entry: 'someAction',
exit: { type: 'someObjectAction' },
on: {
// @ts-expect-error
UNEXPECTED_EVENT: {}
}
});
});

it('should keep the context type on the state after using `state.matches`', () => {
const model = createModel<{ count: number }, { type: 'INC' }>({ count: 0 });

Expand Down

0 comments on commit cda1b9e

Please sign in to comment.