Literal & Tagged Unions in TypeScript (Live Playground)
In this tutorial, we will explore literal and tagged unions in TypeScript. Understanding how to use literal and tagged unions will help you create more type-safe and readable code.
Literal Unions
Literal unions allow you to create a type that is a union of specific values (literals). This is useful when you want to restrict a variable or a function parameter to a fixed set of values:
type Direction = 'north' | 'south' | 'east' | 'west';
function move(direction: Direction): void {
console.log(`Moving in the ${direction} direction.`);
}
move('north'); // Output: Moving in the north direction.
move('south'); // Output: Moving in the south direction.
In this example, we create a literal union type Direction
that can have one of four specific string values. The move
function accepts a parameter of the Direction
type.
Tagged Unions
Tagged unions (also called discriminated unions) are a powerful feature that allows you to create a union of different types with a common property (the tag) that can be used to discriminate between the types. This is useful for creating type-safe code in scenarios where you need to work with different types that share a common structure:
interface Circle {
kind: 'circle';
radius: number;
}
interface Square {
kind: 'square';
sideLength: number;
}
type Shape = Circle | Square;
function getArea(shape: Shape): number {
switch (shape.kind) {
case 'circle':
return Math.PI * shape.radius ** 2;
case 'square':
return shape.sideLength ** 2;
default:
return assertNever(shape);
}
}
function assertNever(value: never): never {
throw new Error(`Unexpected value: ${JSON.stringify(value)}`);
}
const circle: Circle = { kind: 'circle', radius: 5 };
const square: Square = { kind: 'square', sideLength: 4 };
console.log(getArea(circle)); // Output: 78.53981633974483
console.log(getArea(square)); // Output: 16
In this example, we create two interfaces Circle
and Square
with a common kind
property. We then create a tagged union type Shape
and a getArea
function that calculates the area of a shape based on its kind
property. We also define an assertNever
function to handle unexpected values in a type-safe manner.
Conclusion
In this tutorial, we have explored literal and tagged unions in TypeScript. Understanding how to use literal and tagged unions effectively will enable you to create more type-safe and readable code.