Last active
May 10, 2021 15:34
-
-
Save jacksteamdev/315377a2d627baea3331eac4592cc259 to your computer and use it in GitHub Desktop.
xstate helpers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export function assertEventType< | |
TE extends EventObject, | |
TType extends TE['type'] | |
>(event: TE, eventType: TType): asserts event is TE & { type: TType } { | |
if (event.type !== eventType) { | |
throw new Error( | |
`Invalid event: expected "${eventType}", got "${event.type}"`, | |
) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
assign, | |
Assigner, | |
EventObject, | |
PropertyAssigner, | |
PureAction, | |
} from 'xstate' | |
export const assignWhen = < | |
TContext, | |
TEvent extends EventObject, | |
TEventType extends TEvent['type'] | |
>( | |
type: TEventType, | |
assignment: | |
| Assigner<TContext, Extract<TEvent, { type: TEventType }>> | |
| PropertyAssigner<TContext, Extract<TEvent, { type: TEventType }>>, | |
): PureAction<TContext, TEvent> => | |
// @ts-expect-error not sure about this | |
actions.pure((context, event) => { | |
if (event.type !== type) | |
throw new TypeError(`Event type does not match "${type}"`) | |
return assign(assignment) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment