Discriminated unions help you work with different types of data in one place safely. They let you tell which type you have by checking a special property.
Discriminated unions in Typescript
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number };
function area(shape: Shape) {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
case "square":
return shape.size ** 2;
}
}The kind property is the discriminant that tells TypeScript which type it is.
Use a switch or if to check the discriminant and handle each case.
type property.type Animal =
| { type: "dog"; barkVolume: number }
| { type: "cat"; livesLeft: number };type to know if the animal is a dog or cat and use the right property.function speak(animal: Animal) { if (animal.type === "dog") { console.log(`Bark volume: ${animal.barkVolume}`); } else { console.log(`Lives left: ${animal.livesLeft}`); } }
status as the discriminant.type Response =
| { status: "success"; data: string }
| { status: "error"; message: string };This program defines a Vehicle type that can be a car or a bike. The describe function uses the kind property to know which type it is and returns a description. We create a car and a bike and print their descriptions.
type Vehicle =
| { kind: "car"; wheels: 4; brand: string }
| { kind: "bike"; wheels: 2; hasBell: boolean };
function describe(vehicle: Vehicle) {
switch (vehicle.kind) {
case "car":
return `Car brand: ${vehicle.brand}, wheels: ${vehicle.wheels}`;
case "bike":
return `Bike with bell: ${vehicle.hasBell}, wheels: ${vehicle.wheels}`;
}
}
const myCar: Vehicle = { kind: "car", wheels: 4, brand: "Toyota" };
const myBike: Vehicle = { kind: "bike", wheels: 2, hasBell: true };
console.log(describe(myCar));
console.log(describe(myBike));Always use a unique string literal property as the discriminant for clear type checking.
Discriminated unions make your code safer by letting TypeScript know exactly which type you are working with.
Discriminated unions use a special property to tell types apart.
They help write clear and safe code when working with multiple types.
Use switch or if to check the discriminant and handle each case.