Skip to content

Commit

Permalink
Fixed an issue with states coming from model.createMachine resultin…
Browse files Browse the repository at this point in the history
…g in contexts of type `any` after type refinements
  • Loading branch information
Andarist committed Jul 19, 2021
1 parent 68692c1 commit 141c91c
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 6 deletions.
12 changes: 12 additions & 0 deletions .changeset/warm-spies-cry.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
'xstate': patch
---

Fixed an issue with states coming from `model.createMachine` resulting in contexts of type `any` after type refinements such as here:

```ts
// `state.context` became `any` erroneously
if (state.matches('inactive')) {
console.log(state.context.count);
}
```
18 changes: 13 additions & 5 deletions packages/core/src/State.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@ import { StateNode } from './StateNode';
import { getMeta, nextEvents } from './stateUtils';
import { initEvent } from './actions';

type Equals<A1 extends any, A2 extends any> = (<A>() => A extends A2
? 1
: 0) extends <A>() => A extends A1 ? 1 : 0
? 1
: 0;

export function stateValuesEqual(
a: StateValue | undefined,
b: StateValue | undefined
Expand Down Expand Up @@ -293,11 +299,13 @@ export class State<
public matches<TSV extends TTypestate['value']>(
parentStateValue: TSV
): this is State<
(TTypestate extends any
? { value: TSV; context: any } extends TTypestate
? TTypestate
: never
: never)['context'],
Equals<TTypestate, any> extends 1
? TContext
: (TTypestate extends any
? { value: TSV; context: any } extends TTypestate
? TTypestate
: never
: never)['context'],
TEvent,
TStateSchema,
TTypestate
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/model.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export interface Model<
createMachine: (
config: MachineConfig<TContext, any, TEvent>,
implementations?: Partial<MachineOptions<TContext, TEvent>>
) => StateMachine<TContext, any, TEvent, any>;
) => StateMachine<TContext, any, TEvent>;
}

export type ModelContextFrom<
Expand Down

0 comments on commit 141c91c

Please sign in to comment.