The Discriminant Property
What you'll learn: How a shared property with distinct literal values helps TypeScript automatically narrow union types.
What Is a Discriminant Property?
A discriminant property (also called a "tag" or "type field") is a common property that appears in every member of a union, but with different literal values for each variant. This property acts like a unique identifier that TypeScript can inspect to figure out which specific type you're working with.
Think of it like color-coded folders in a filing cabinet. Each folder has a "category" label (the discriminant property), but the label says different things: "Invoices," "Receipts," or "Contracts." When you read the label, you instantly know what's inside—and so does TypeScript.
The Anatomy of a Discriminant
The discriminant property must meet specific criteria:
- Same property name across all union members
- Literal types as values (like
"success","error",404,true) - Unique values that distinguish each variant
When you check the discriminant property (using ===, switch, or similar), TypeScript narrows the union to the matching type, giving you access to that variant's unique properties.
Why Discriminants Matter
Without a discriminant, TypeScript can only let you access properties that exist on all union members. With a discriminant, a simple check unlocks the full shape of each specific variant. This makes discriminated unions one of the most powerful patterns for type-safe data modeling in TypeScript.
Key Takeaway: A discriminant property is a shared field with unique literal values that lets TypeScript distinguish between union variants and narrow the type automatically.