Skip to content

Commit

Permalink
Fixed an issue with context type defined using schema.context being…
Browse files Browse the repository at this point in the history
… sometimes widened based on `config.context` (#3084)
  • Loading branch information
Andarist committed Feb 24, 2022
1 parent 1aaf509 commit 50c271d
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/red-frogs-yell.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'xstate': patch
---

Fixed an issue with context type defined using `schema.context` being sometimes widened based on `config.context`. If both are given the `schema.context` should always take precedence and should represent the complete type of the context.
3 changes: 2 additions & 1 deletion packages/core/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export type Equals<A1 extends any, A2 extends any> = (<A>() => A extends A2
export type IsAny<T> = Equals<T, any>;
export type Cast<A, B> = A extends B ? A : B;
export type NoInfer<T> = [T][T extends any ? 0 : any];
export type LowInfer<T> = T & {};

export type EventType = string;
export type ActionType = string;
Expand Down Expand Up @@ -951,7 +952,7 @@ export interface MachineConfig<
/**
* The initial context (extended state)
*/
context?: TContext | (() => TContext);
context?: LowInfer<TContext | (() => TContext)>;
/**
* The machine's own version.
*/
Expand Down
33 changes: 33 additions & 0 deletions packages/core/test/types.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -395,6 +395,25 @@ describe('Typestates', () => {
});

describe('context', () => {
it('should infer context type from `config.context` when there is no `schema.context`', () => {
createMachine(
{
context: {
foo: 'test'
}
},
{
actions: {
someAction: (ctx) => {
((_accept: string) => {})(ctx.foo);
// @ts-expect-error
((_accept: number) => {})(ctx.foo);
}
}
}
);
});

it('should not use actions as possible inference sites', () => {
createMachine(
{
Expand Down Expand Up @@ -426,6 +445,20 @@ describe('context', () => {

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

it('should not widen literal types defined in `schema.context` based on `config.context`', () => {
createMachine({
schema: {
context: {} as {
literalTest: 'foo' | 'bar';
}
},
context: {
// @ts-expect-error
literalTest: 'anything'
}
});
});
});

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

0 comments on commit 50c271d

Please sign in to comment.