Skip to content

Instantly share code, notes, and snippets.

@tijnjh
Last active May 26, 2026 16:59
Show Gist options
  • Select an option

  • Save tijnjh/e8b3c575f9813988577c3382d21558f7 to your computer and use it in GitHub Desktop.

Select an option

Save tijnjh/e8b3c575f9813988577c3382d21558f7 to your computer and use it in GitHub Desktop.
match.ts
export function match<
TValue extends PropertyKey,
TCases extends Record<TValue, () => unknown>,
>(value: TValue, cases: TCases): ReturnType<TCases[TValue]>;
export function match<
TValue extends PropertyKey,
TCases extends Partial<Record<TValue, () => unknown>>,
>(
value: TValue,
cases: TCases & { _: () => unknown },
): ReturnType<NonNullable<TCases[keyof TCases]>>;
// @ts-expect-error - implicit any to allow for overloads
export function match(value, cases) {
return (cases[value] ?? cases._)();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment