Union types memungkinkan variabel memiliki salah satu dari beberapa tipe:
function cetak(id: string | number) {
console.log(`ID: ${id}`);
}
cetak(123); // OK
cetak("abc"); // OK
Literal types — tipe yang nilainya spesifik:
type Direction = "up" | "down" | "left" | "right";
function move(dir: Direction) {
// dir hanya bisa salah satu dari 4 nilai
}
move("up"); // OK
move("diagonal"); // ❌ Error!
Discriminated unions — union dengan field pembeda:
type Circle = { kind: "circle"; radius: number };
type Square = { kind: "square"; side: number };
type Shape = Circle | Square;
function area(shape: Shape): number {
if (shape.kind === "circle") return Math.PI * shape.radius ** 2;
return shape.side ** 2;
}