Skip to content

Commit

Permalink
Fixed an issue with not being able to call createMachine in a gener…
Browse files Browse the repository at this point in the history
…ic context (#3027)

* Remove type assertion in createMachine

* Add a type test for a generic context

* Update .changeset/lemon-mugs-attack.md

Co-authored-by: Daniel Playfair Cal <dcal@atlassian.com>
Co-authored-by: Mateusz Burzyński <mateuszburzynski@gmail.com>
  • Loading branch information
3 people committed Feb 23, 2022
1 parent 8d3f2cf commit 97ad964
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 12 deletions.
5 changes: 5 additions & 0 deletions .changeset/lemon-mugs-attack.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'xstate': patch
---

Fixed an issue with not being able to call `createMachine` in a generic context when the type for the context was generic and not concrete.
19 changes: 8 additions & 11 deletions packages/core/src/Machine.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { Model } from './model.types';
import { StateNode } from './StateNode';
import {
AnyEventObject,
Expand Down Expand Up @@ -86,16 +85,14 @@ export function createMachine<
TServiceMap extends ServiceMap = ServiceMap,
TTypesMeta extends TypegenConstraint = TypegenDisabled
>(
config: TContext extends Model<any, any, any, any>
? 'Model type no longer supported as generic type. Please use `model.createMachine(...)` instead.'
: MachineConfig<
TContext,
any,
TEvent,
BaseActionObject,
TServiceMap,
TTypesMeta
>,
config: MachineConfig<
TContext,
any,
TEvent,
BaseActionObject,
TServiceMap,
TTypesMeta
>,
options?: InternalMachineOptions<
TContext,
TEvent,
Expand Down
19 changes: 18 additions & 1 deletion packages/core/test/types.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
import { from } from 'rxjs';
import { Machine, assign, createMachine, interpret } from '../src/index';
import {
Machine,
assign,
createMachine,
interpret,
StateMachine,
MachineConfig
} from '../src/index';
import { raise } from '../src/actions';

function noop(_x: unknown) {
Expand Down Expand Up @@ -410,6 +417,16 @@ describe('context', () => {
}
);
});

it('should work with generic context', () => {
function createMachineWithExtras<TContext>(
context: TContext
): StateMachine<TContext, any, any> {
return createMachine({ context });
}

createMachineWithExtras({ counter: 42 });
});
});

describe('interpreter', () => {
Expand Down

0 comments on commit 97ad964

Please sign in to comment.