Skip to content

Instantly share code, notes, and snippets.

@zoontek
Created April 15, 2020 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zoontek/7c62e52b4c0196579060bd0b105bf824 to your computer and use it in GitHub Desktop.
Save zoontek/7c62e52b4c0196579060bd0b105bf824 to your computer and use it in GitHub Desktop.
TS match functions
type Key = string | number | symbol;
type ExhaustiveMatch<K extends Key, T> = Record<K, T>;
type PartialMatch<K extends Key, T> = Partial<Record<K, T>> & { _: T };
export const match = <T, K extends Key = Key>(
key: K,
map: ExhaustiveMatch<K, T> | PartialMatch<K, T>,
): T => (map.hasOwnProperty(key) ? map[key] : (map as PartialMatch<K, T>)._) as T;
export const lazymatch = <T, K extends Key = Key>(
key: K,
map: ExhaustiveMatch<K, () => T> | PartialMatch<K, () => T>,
): T => ((map.hasOwnProperty(key) ? map[key] : (map as PartialMatch<K, () => T>)._) as () => T)();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment