Last active
June 22, 2026 10:29
-
-
Save tijnjh/e8b3c575f9813988577c3382d21558f7 to your computer and use it in GitHub Desktop.
match.ts
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 MatchableValue<O, K extends keyof O> = Extract<O[K], PropertyKey>; | |
| type MatchObjectCases<O extends object, K extends keyof O> = Partial<{ | |
| [V in MatchableValue<O, K>]: (obj: Extract<O, Record<K, V>>) => unknown; | |
| }> & { _?: (obj: O) => unknown }; | |
| export function match<V extends PropertyKey, C>( | |
| value: V, | |
| cases: C & { [K in keyof C]: C[K] extends () => unknown ? unknown : never } & ("_" extends keyof C | |
| ? Record<Exclude<keyof C, V | "_">, never> | |
| : Record<Exclude<keyof C, V>, never> & Record<Exclude<V, keyof C>, never>), | |
| _arg2?: never, | |
| ): C[keyof C] extends () => infer R ? R : never; | |
| export function match<O extends object, K extends keyof O, const C extends MatchObjectCases<O, K>>( | |
| obj: O, | |
| key: K, | |
| cases: C & | |
| ("_" extends keyof C | |
| ? Record<Exclude<keyof C, MatchableValue<O, K> | "_">, never> | |
| : Record<Exclude<keyof C, MatchableValue<O, K>>, never> & | |
| Record<Exclude<MatchableValue<O, K>, keyof C>, never>), | |
| ): { [K in keyof C]: C[K] extends (...args: any[]) => infer R ? R : never }[keyof C]; | |
| // @ts-expect-error implicit any | |
| export function match(arg0, arg1, arg2) { | |
| const [value, cases, obj] = arg2 !== undefined ? [arg0[arg1], arg2, arg0] : [arg0, arg1]; | |
| return (cases[value] ?? cases._)(obj); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.