Codesnacks

moon indicating dark mode
sun indicating light mode

Tagged Unions in Typescript

April 19, 2020

A Tagged Union is a type that can represent several cases (or subtypes). More specifically tagged unions are a refinement of union types: It introduces names (tags) for each case/subtype which can be used for Exhaustiveness checking 1.

A Tagged Union in action using io-ts:

import * as t from "io-ts";
type Dog = t.TypeOf<typeof Dog>;
const DogURI = "Dog";
const Dog = t.type({
_tag: t.literal(DogURI),
name: t.string
});
type Cat = t.TypeOf<typeof Cat>;
const CatURI = "Cat";
const Cat = t.type({
_tag: t.literal(CatURI),
name: t.string
});
const Animal = t.union([Dog, Cat]);
type Animal = t.TypeOf<typeof Animal>;
// Exhaustiveness checking!
const sayHello = (someAnimal: Animal): string => {
switch (someAnimal._tag) {
case DogURI: {
return `Hello dog ${someAnimal.name}`;
}
case CatURI: {
return `Hello cat '${someAnimal.name}'`;
}
}
};
const cat: Cat = {
_tag: "Cat",
name: "Snowball"
};
/*
Output: Hello cat 'Snowball'
*/
console.log(sayHello(cat));

The example uses the following dependencies:

"dependencies": {
"fp-ts": "2.5.3",
"io-ts": "2.1.3"
}

Further Readings

  • Tagged Union on Wikipedia
  • Discriminated Unions in Typescript

A collection of some small code snippets & experiments
No tutorials. Nothing fancy. Just some code.