Skip to content

Commit

Permalink
Fixed an issue with EmittedFrom sometimes not being able to infer t…
Browse files Browse the repository at this point in the history
…he snapshot types from machines (#3783)
  • Loading branch information
Andarist committed Jan 24, 2023
1 parent 513c004 commit b68f0e8
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/little-frogs-fly.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'xstate': patch
---

Fixed an issue with `EmittedFrom` sometimes not being able to infer the snapshot types from machines.
20 changes: 19 additions & 1 deletion packages/core/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1814,7 +1814,25 @@ export interface Behavior<TEvent extends EventObject, TEmitted = any> {
}

export type EmittedFrom<T> = ReturnTypeOrValue<T> extends infer R
? R extends Interpreter<infer _, infer __, infer ___, infer ____, infer _____>
? // we need to specialcase the StateMachine here (even though it's a Behavior)
// because its `transition` method is too different from the `Behavior["transition"]`
R extends StateMachine<
infer _,
infer __,
infer ___,
infer ____,
infer _____,
infer ______,
infer _______
>
? R['initialState']
: R extends Interpreter<
infer _,
infer __,
infer ___,
infer ____,
infer _____
>
? R['initialState']
: R extends ActorRef<infer _, infer TEmitted>
? TEmitted
Expand Down
24 changes: 24 additions & 0 deletions packages/core/test/typeHelpers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -403,4 +403,28 @@ describe('EmittedFrom', () => {
// @ts-expect-error
acceptState("isn't any");
});

it('should return state from a machine without context', () => {
const machine = createMachine({});

function acceptState(_state: EmittedFrom<typeof machine>) {}

acceptState(machine.initialState);
// @ts-expect-error
acceptState("isn't any");
});

it('should return state from a machine with context', () => {
const machine = createMachine({
context: {
counter: 0
}
});

function acceptState(_state: EmittedFrom<typeof machine>) {}

acceptState(machine.initialState);
// @ts-expect-error
acceptState("isn't any");
});
});

0 comments on commit b68f0e8

Please sign in to comment.