Narrowing with Discriminant Properties
What you'll learn: How to use a common literal-typed property across union members to let TypeScript automatically narrow types.
The Discriminant Pattern
When you have a union of object types, TypeScript can't always tell which member you're working with. A discriminant property (also called a discriminant or tag) is a common property that exists on all union members, where each member has a different literal value for that property.
Think of it like sorting mail: if every envelope has a "type" stamp that says "bill", "letter", or "postcard", you can instantly know what category you're dealing with just by checking that one stamp.
How It Works
type Circle = {
kind: "circle";
radius: number;
};
type Rectangle = {
kind: "rectangle";
width: number;
height: number;
};
type Shape = Circle | Rectangle;
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 Rectangle here
return shape.width * shape.height;
}
}
The kind property is the discriminant. By checking shape.kind === "circle", TypeScript narrows the type from Shape to specifically Circle, giving you access to radius.
Why This Matters
Discriminant properties make unions predictable and safe. TypeScript uses the literal value check to eliminate impossible cases, giving you full autocomplete and type safety in each branch without manual type guards or assertions.
Key Takeaway: A discriminant property with literal types across union members lets TypeScript automatically narrow to the correct type when you check that property's value.