Created
April 15, 2020 14:11
-
-
Save zoontek/7c62e52b4c0196579060bd0b105bf824 to your computer and use it in GitHub Desktop.
TS match functions
This file contains hidden or 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
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