hasType

Type guard for discriminated unions based on type property.

#types #typescript #type-guard
export const hasType = <
T extends { type: string },
U extends T['type'],
>(
value: T,
type: U,
): value is Extract<T, { type: U }> => value.type === type;
// Usage
type Event =
| { type: 'click'; x: number; y: number }
| { type: 'keydown'; key: string };
function handleEvent(event: Event) {
if (hasType(event, 'click')) {
console.log(event.x, event.y); // Narrowed to click type
} else {
console.log(event.key); // Narrowed to keydown type
}
}

Share this snippet

Comments