Skip to content

Instantly share code, notes, and snippets.

@tom-sherman
Created December 23, 2021 08:09
Show Gist options
  • Save tom-sherman/05287677044d071e55c00cff190be739 to your computer and use it in GitHub Desktop.
Save tom-sherman/05287677044d071e55c00cff190be739 to your computer and use it in GitHub Desktop.
XState Event Type Invariant
import { EventObject } from 'xstate';
export function assertEventType<
TEvent extends EventObject,
TType extends TEvent['type']
>(
event: TEvent,
type: TType
): asserts event is Extract<TEvent, { type: TType }>;
export function assertEventType<
TEvent extends EventObject,
TTypes extends readonly TEvent['type'][]
>(
event: TEvent,
type: TTypes
): asserts event is Extract<TEvent, { type: TTypes[number] }>;
export function assertEventType(
event: EventObject,
type: string | string[]
): void {
if (typeof type === 'string' && event.type !== type) {
throw new Error(
`Expected event type "${type}", found type "${event.type}"`
);
}
if (Array.isArray(type) && !type.includes(event.type)) {
throw new Error(
`Expected one of event type "${JSON.stringify(type)}", found type "${
event.type
}"`
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment