Skip to content

Instantly share code, notes, and snippets.

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
// 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': {
return null;
case '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.