Created
December 23, 2021 08:09
-
-
Save tom-sherman/05287677044d071e55c00cff190be739 to your computer and use it in GitHub Desktop.
XState Event Type Invariant
This file contains 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 { 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