Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Definition
- type Compact<A> = { [k in keyof A]: A[k] }
- type FStruct<R extends Record<any, any>, K extends keyof R = keyof R> = {
- [k in K]: { [kv in R[k]]: R extends { [r in k]: kv } ? Compact<R> : never }
- }
- type Match<StructK, R> = { [KV in keyof StructK]: (v: StructK[KV]) => R }
- const folder = <A extends object>() => <D extends keyof A>(discr: D) => <R>(match: Match<FStruct<A>[D], R>) => (a: A) =>
- match[a[discr]](a as any)
- // Usage
- type A = { type: 'ta'; x: 'a' } | { type: 'tb'; x: 'b'; y: 'c' } // Adhoc Union
- const aByType = folder<A>()('type') // Define the discriminant
- const matcher = aByType({ // a Matcher function
- ta: v => v.x,
- tb: v => v.y
- })
- const res = matcher({ type: 'ta', x: 'a' }) // Application
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement