Sub topic 1
TypeScript Discriminated Unions: Modeling Variants the Compiler Can Check
Prerequisites
This chapter assumes basic TypeScript types, object types, functions, if statements, and switch statements. Use strict mode in tsconfig.json.
Union types: a value that is one of several types
A union type describes a value that can have one of several types. Use | between the alternatives.
type Identifier = string | number;
function formatId(id: Identifier): string {
if (typeof id === "number") {
return `#${id}`;
}
return id.toUpperCase();
}
console.log(formatId(42));
console.log(formatId("abc"));Inside the if statement, TypeScript narrows id from string | number to number. After the statement, the remaining possibility is string.
Literal types as tags
A literal type allows exactly one value, such as "circle" or true. Literal types are useful as labels, also called tags, because they identify which variant an object represents.
type Circle = { kind: "circle"; radius: number };
type Square = { kind: "square"; size: number };Here, kind is not any string. It must be exactly "circle" or "square".
How TypeScript narrows types
TypeScript narrows a union when your code checks a property or value. A check such as shape.kind === "circle" gives the compiler evidence about the object’s type.
Choosing a discriminant property
A discriminant is a shared property whose literal value identifies each union member. Choose a property that is:
- Present in every member.
- Named consistently.
- Different for every variant.
- Required, not optional.
Common names include kind, type, status, and action.
Defining a discriminated union
Combine the tagged object types into one union. TypeScript can then narrow the union from the tag.
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number };
function area(shape: Shape): number {
if (shape.kind === "circle") {
return Math.PI * shape.radius ** 2;
}
return shape.size ** 2;
}
console.log(area({ kind: "circle", radius: 2 }));
console.log(area({ kind: "square", size: 3 }));The circle branch safely reads radius, while the remaining branch safely reads size.
Exercise
Why is kind a better discriminant than an optional radius property?
Show answer
Every member has kind with a distinct literal value, so TypeScript can identify the exact member reliably.