-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
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
[core] Modeling events with createModel() #1955
Conversation
🦋 Changeset detectedLatest commit: 5febfe8 The changes in this PR will be included in the next version bump. This PR includes changesets to release 3 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
Instead of needing to do: const machine = createMachine<typeof myModel['types']['context'], typeof myModel['types']['events']>({}); Could there be a function definition for export function createMachine<ContextModel, TTypeStates>(config: MachineConfig): StateMachine<ContextModel['types']['context'], any, ContextModel['types']['events'], TTypeStates>; |
Ideally yes, but I don't know if it's possible to have function overloading with different generic types... @Andarist @mattpocock ? |
It looks like the |
Yep, totally possible. |
looks great! I have been using createModel in my machines lately to make typing more consistent and it's been working well. would this be compatible with the |
It should be! I haven't tested it out, might need to update the types or create an Immer-specific |
@davidkpiano how about to implement an array of events acceptable? import isType from '@sindresorhus/is';
import type { EventObject } from 'xstate';
import type { AssertedTypesUnion } from './types';
export function assertEventType<
TEvent extends EventObject,
TExpectedType extends TEventTypeArray | TEventType,
TEventType extends TEvent['type'],
TEventTypeArray extends TEventType[]
>(
event: TEvent,
expected: TExpectedType,
): asserts event is TEvent & {
type: AssertedTypesUnion<TExpectedType>;
} {
const events = isType.array<TExpectedType>(expected) ? expected : [expected];
const { type } = event;
if (!events.includes(type as TExpectedType)) {
throw new Error(
`Invalid event: expected one of "${events.join(
',',
)}" but got "${type}" instead.`,
);
}
} wherever |
… related to Model
Fixed type errors in tests after introducing createMachine's overload related to Model
Making this PR to discuss and see how we can improve this. This PR provides type inference for events in
createModel()
that are specified as "event creators":This is a little awkward, sure:
But the important part is this:
The second argument to
createModel(initialCtx, eventCreators)
enables two things:Let me know your thoughts!