Created
January 6, 2018 15:51
-
-
Save andrejewski/ae222845eaff10b14411d2fbf7fa62cd to your computer and use it in GitHub Desktop.
Tagged union in TypeScript
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
| interface Tag { | |
| kind: string | |
| data: any | |
| } | |
| interface Union { | |
| match<T>(tag: Tag, handleMap: { [kind: string]: (data: any) => T }, catchAll?: () => T): T, | |
| tags: { [kind: string]: (data: any) => Tag } | |
| } | |
| export function union(kinds: string[]): Union { | |
| return { | |
| match(tag, handleMap, catchAll) { | |
| const handle = handleMap[tag.kind] | |
| return handle ? handle(tag.data) : catchAll() | |
| }, | |
| tags: kinds.reduce( | |
| (tags, kind) => ({ | |
| ...tags, | |
| [kind]: data => ({ kind, data } as Tag) | |
| }), | |
| {} | |
| ) | |
| } | |
| } | |
| const { match, tags } = union(['Poop']) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment