Basic Discriminated Union Example
You'll learn how to create a simple union where each member has a common "type" or "kind" property to tell the shapes apart.
The Core Idea
A discriminated union uses a shared property—typically called type, kind, or tag—to distinguish between different shapes in a union. Instead of guessing which shape you have, you check this discriminant property, and TypeScript automatically narrows the type for you.
Think of it like sorting mail: if every envelope has a label ("bill," "newsletter," "invitation"), you can quickly decide how to handle each one. The discriminant is that label.
A Simple Example
type Circle = {
kind: "circle";
radius: number;
};
type Square = {
kind: "square";
sideLength: number;
};
type Shape = Circle | Square;
function getArea(shape: Shape): number {
if (shape.kind === "circle") {
// TypeScript knows: shape is Circle here
return Math.PI * shape.radius ** 2;
} else {
// TypeScript knows: shape is Square here
return shape.sideLength ** 2;
}
}
Both Circle and Square have a kind property, but with different literal values. When you check shape.kind === "circle", TypeScript narrows shape to the Circle type, giving you safe access to radius.
Why This Works
The discriminant (kind) is a common property with unique literal values for each union member. This lets TypeScript's narrowing engine automatically understand which type you're dealing with after a simple equality check.
Key Takeaway: A discriminated union uses a shared property with unique literal values per type, enabling automatic, reliable type narrowing based on simple checks.