A discriminated union (also called a tagged union or algebraic data type) is a union of object types where each variant includes a special property — the discriminant — with a unique literal value. TypeScript can then use that property to narrow which variant you’re working with.
For example:
type ApiResponse =
| { status: "loading" }
| { status: "success"; data: string }
| { status: "error"; message: string };
function handleResponse(res: ApiResponse) {
if (res.status === "success") {
// Here, TypeScript knows res.data exists
return "Got data: " + res.data;
} else if (res.status === "error") {
// Here, TypeScript knows res.message exists
return "Error: " + res.message;
}
return "Loading...";
}
The discriminant (status) acts like a “tag” that identifies which variant you’re dealing with. When you check it with if or switch, TypeScript automatically narrows the type so only the valid fields for that variant are available.
Use a discriminated union to model a small set of shapes. Each variant provides exactly the properties needed for its area formula.