Skip to content

Instantly share code, notes, and snippets.

@andrejewski
Created January 6, 2018 15:51
Show Gist options
  • Select an option

  • Save andrejewski/ae222845eaff10b14411d2fbf7fa62cd to your computer and use it in GitHub Desktop.

Select an option

Save andrejewski/ae222845eaff10b14411d2fbf7fa62cd to your computer and use it in GitHub Desktop.
Tagged union in TypeScript
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