Skip to content

Instantly share code, notes, and snippets.

@tcr
Created March 22, 2018 13:47
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 tcr/0d6d8bb57b4708ac4f267ebf7c07e7d4 to your computer and use it in GitHub Desktop.
Save tcr/0d6d8bb57b4708ac4f267ebf7c07e7d4 to your computer and use it in GitHub Desktop.
// 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