Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// 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
You can’t perform that action at this time.