Union & Intersection Types
Compose flexible data structures using Union types (|) and Discriminated Unions.
1. Union Types (`|`)
A union type describes a value that can be one of several types:
type Status = "pending" | "approved" | "rejected";
type InputValue = string | number | boolean;
function processStatus(s: Status) {
console.log(`Current status: ${s}`);
}2. Discriminated Unions (Tagged Unions)
Discriminated unions use a common literal property (e.g. kind or type) to let TypeScript narrow down exact object shapes inside switch/if statements:
interface Circle {
kind: "circle";
radius: number;
}
interface Square {
kind: "square";
size: number;
}
interface Rectangle {
kind: "rectangle";
width: number;
height: number;
}
type Shape = Circle | Square | Rectangle;
function getArea(shape: Shape): number {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
case "square":
return shape.size * shape.size;
case "rectangle":
return shape.width * shape.height;
default:
// Exhaustiveness check
const _exhaustiveCheck: never = shape;
return _exhaustiveCheck;
}
}Next Up
Learn Type Narrowing: typeof, instanceof, in operator, and Custom Type Predicates.
Next Lesson: Type Narrowing & Guards →