Skip to content

Instantly share code, notes, and snippets.

@rklaehn
Last active February 23, 2018 21:14
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 rklaehn/6e60a720fd3d4bd5dd7241f4cb7f7ebe to your computer and use it in GitHub Desktop.
Save rklaehn/6e60a720fd3d4bd5dd7241f4cb7f7ebe to your computer and use it in GitHub Desktop.
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)
@rklaehn
Copy link
Author

rklaehn commented Feb 23, 2018

Repl: here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment