Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed an issue with context type defined using schema.context being sometimes widened based on config.context #3084

Merged
merged 1 commit into from
Feb 24, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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