Last active
February 23, 2018 21:14
-
-
Save rklaehn/6e60a720fd3d4bd5dd7241f4cb7f7ebe to your computer and use it in GitHub Desktop.
This file contains 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 Protocol = { | |
foo: { x: string }; | |
bar: { y: number }; | |
} | |
type Fold<T, U> = { | |
readonly [P in keyof T]: (value: T[P]) => U | |
} | |
type WithTag<T> = { | |
[TKey in keyof T]: { type: TKey } & T[TKey] | |
} | |
type ToDiscriminatedUnion<P> = WithTag<P>[keyof P] | |
const match: <P>(value: ToDiscriminatedUnion<P>) => <R>(f: Fold<P, R>) => R = | |
value => f => f[value.type](value) | |
const res = match<Protocol>({ type: 'foo', x: '1' })({ | |
foo: ({ x }) => x.length, | |
bar: ({ y }) => y, | |
}) | |
alert(res) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Repl: here