Created
March 22, 2018 13:47
-
-
Save tcr/0d6d8bb57b4708ac4f267ebf7c07e7d4 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
// Declare your union variants | |
// Easy to name variant contructors + define tags in one place | |
function Age(age: number) { | |
return { tag: 'Age' as 'Age', age } | |
} | |
function Name(name: string) { | |
return { tag: 'Name' as 'Name', name } | |
} | |
// Unify them | |
type TaggedUnion = | |
| ReturnType<typeof Age> | |
| ReturnType<typeof Name>; | |
// Can invoke with either variant | |
ok(Age(0)); | |
ok(Name(name)); | |
// Can switch on TaggedUnion.tag | |
// Use a return type and --strictNullChecks if you want exhaustiveness checking .-. | |
function ok(j: TaggedUnion): null { | |
switch (j.tag) { | |
case 'Age': { | |
console.log(j.age); | |
return null; | |
} | |
case 'Name': { | |
console.log(j.name); | |
return null; | |
} | |
} | |
// Exhaustive check; this isn't reachable | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment