Sub topic 5
Defining a Discriminated Union
Assume you know basic TypeScript types, interfaces, functions, object properties, and if or switch statements. This chapter uses strict mode, so the compiler checks types carefully.
One value, several possible shapes
A union type describes a value that can be one of several types. The vertical bar (|) joins the alternatives:
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number }
| { kind: "rectangle"; width: number; height: number };Shape can be a circle, square, or rectangle. Each alternative is an object type with its own properties.
The kind property is the discriminant. A discriminant is a shared property whose value identifies the current union member. Each value is a string literal type, such as "circle" or "square", rather than the general string type.
| Shape member | Discriminant value | Other data |
|---|---|---|
| Circle | `"circle"` | `radius` |
| Square | `"square"` | `size` |
| Rectangle | `"rectangle"` | `width`, `height` |
The discriminant values must distinguish the members. If two members both use kind: "circle", TypeScript cannot reliably tell them apart.
Narrowing with the discriminant
Before checking kind, TypeScript only knows that a Shape could be any member. It does not allow you to read radius, because squares and rectangles do not have that property.
A comparison narrows the type. Narrowing means removing impossible alternatives from a union based on control-flow information.
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number }
| { kind: "rectangle"; width: number; height: number };
function area(shape: Shape): number {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
case "square":
return shape.size ** 2;
case "rectangle":
return shape.width * shape.height;
}
}
function label(shape: Shape): string {
if (shape.kind === "circle") {
return `Circle with radius ${shape.radius}`;
}
if (shape.kind === "square") {
return `Square with side ${shape.size}`;
}
return `Rectangle ${shape.width} by ${shape.height}`;
}
console.log(area({ kind: "circle", radius: 2 }));
console.log(label({ kind: "rectangle", width: 3, height: 4 }));Inside the "circle" case, shape has the circle type. Inside the "square" case, it has the square type. TypeScript makes the member-specific properties available without a type assertion.
Designing useful variants
A discriminated union works best when each member represents one complete, meaningful case. Keep properties required when they apply to that case.
For example, this state model prevents impossible combinations:
type RequestState<T> =
| { status: "idle" }
| { status: "loading" }
| { status: "success"; data: T }
| { status: "error"; error: Error };A loading state cannot accidentally contain success data, and an error state cannot accidentally omit its error. This is safer than one object with several optional properties, such as data?: T and error?: Error, where invalid combinations are easier to create.
Exercise
Define a Payment union with "card" and "cash" variants. The card variant must contain last4: string; the cash variant must contain received: number.
Show answer
type Payment = { method: "card"; last4: string } | { method: "cash"; received: number };