Skip to content

Instantly share code, notes, and snippets.

@jacksteamdev
Last active May 10, 2021 15:34
Show Gist options
  • Save jacksteamdev/315377a2d627baea3331eac4592cc259 to your computer and use it in GitHub Desktop.
Save jacksteamdev/315377a2d627baea3331eac4592cc259 to your computer and use it in GitHub Desktop.
xstate helpers
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}"`,
)
}
}
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