Sub topic 5
Defining a discriminated union
This chapter assumes you know basic TypeScript syntax (types, interfaces, functions) and optional properties. It also assumes strict: true in your tsconfig.json. Without strict mode, the errors shown below do not appear and the pattern loses most of its value.
What makes a union "discriminated"
A discriminated union is a union of object types that all share one property, the discriminant, whose type is a different literal in each member. Three parts have to be present:
- A union type, so the value is one of several object types.
- A common property name that every member declares.
- A literal type for that property in each member, with a different literal in each one.
When all three hold, a check on the discriminant tells the compiler which member you have. The compiler then lets you use that member's other properties. The chapters on narrowing cover the mechanics. This chapter covers how to write the definition so narrowing works.
The problem it solves
Here is a first attempt that does not use a discriminated union:
interface LooseShape {
kind: "circle" | "square";
radius?: number;
size?: number;
}
function looseArea(shape: LooseShape): number {
if (shape.kind === "circle") {
// Under strict mode, shape.radius is number | undefined,
// so using it in arithmetic is a compile error.
return Math.PI * (shape.radius ?? 0) ** 2;
}
return (shape.size ?? 0) ** 2;
}
// Nothing stops this nonsense value:
const broken: LooseShape = { kind: "circle", size: 4 };
console.log(looseArea(broken)); // 0The type says a circle may have a size and no radius. Every consumer must handle undefined and silently falls back to a default. The type allows invalid values and pushes the checking onto each caller.
A discriminated union moves the rules into the type itself.
Writing the definition
Give each variant its own object type. Put a literal-typed kind property in each one. Then join them with |.
interface Circle {
kind: "circle";
radius: number;
}
interface Square {
kind: "square";
size: number;
}
interface Rectangle {
kind: "rectangle";
width: number;
height: number;
}
type Shape = Circle | Square | Rectangle;
function describeShape(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(describeShape({ kind: "rectangle", width: 2, height: 5 }));Each variant now lists only the fields that make sense for it. A circle with a size is a compile error, and a circle without a radius is one too. Inside the if, shape.radius is a plain number, with no undefined to handle.
You can write the members as inline object types or as interfaces. Both work the same way. Named members, as above, are easier to reuse in function signatures and in Extract (covered in a later chapter).
What can be a discriminant
The discriminant must have a unit type, meaning a type that has exactly one possible value. These all qualify:
| Discriminant type | Example member |
|---|---|
| String literal | `{ kind: "circle" }` |
| Number literal | `{ version: 1 }` |
| Boolean literal | `{ ok: true }` |
| `null` or `undefined` | `{ error: null }` |
| Enum member | `{ type: Kind.Circle }` |
String literals are the most common choice because they are readable in logs and in JSON. Boolean discriminants suit two-case unions such as the Result type later in this tutorial. A discriminant can be null or undefined in one member and a different type elsewhere. In practice, most code uses strings.
A property typed string, number, or boolean is not a discriminant, because many values fit that type. The compiler cannot tell the members apart with it.
Shared properties
Members may have other properties in common besides the discriminant. Those properties are available on the whole union without narrowing:
interface ShapeBase {
id: string;
}
interface Circle2 extends ShapeBase {
kind: "circle";
radius: number;
}
interface Square2 extends ShapeBase {
kind: "square";
size: number;
}
type Shape2 = Circle2 | Square2;
function label(shape: Shape2): string {
// id and kind exist on every member, so no narrowing is needed.
return `${shape.kind}#${shape.id}`;
}
console.log(label({ id: "a1", kind: "square", size: 3 }));Reading shape.radius here, before narrowing, is an error. TypeScript reports that radius does not exist on Square2. Only properties present on every member can be read from the union directly.
Rules for a working discriminant
- Same property name in every member.
kindin one andtypein another does not work. - A literal type, not a wide type.
kind: stringmakes the property useless as a tag. - A distinct literal per member. If two members both use
kind: "circle", a check onkindcannot choose between them. - No optional discriminant.
kind?: "circle"addsundefinedto the type. That breaks the one-tag-one-member rule unless you handleundefinedas its own case.
A single member may accept more than one tag value. The check still narrows, as long as no value is shared between members:
type Polygon =
| { kind: "triangle"; sides: 3 }
| { kind: "square" | "rhombus"; sides: 4; edge: number };
function edgeLength(p: Polygon): number | undefined {
if (p.kind === "square" || p.kind === "rhombus") {
return p.edge;
}
return undefined;
}
console.log(edgeLength({ kind: "rhombus", sides: 4, edge: 2 }));Any literal property can work
The property does not need to be called kind. Common names are kind, type, tag, and status. Pick one name and use it across your codebase so readers recognise the pattern. Redux actions use type, and the state example in a later chapter uses status. TypeScript treats them all the same.
There can also be more than one discriminant. In the Polygon example, sides is also a literal in each member, so p.sides === 3 narrows the union too. This is rarely needed, and one clear tag is easier to maintain.
Checking your definition
A quick way to confirm the union is built correctly is to see what the compiler does with a wrong value. Each of these lines should fail:
// Compile errors, shown as comments so this block still runs:
// const a: Shape = { kind: "circle", size: 4 }; // wrong field for the tag
// const b: Shape = { kind: "triangle", size: 4 }; // unknown tag
// const c: Shape = { kind: "circle" }; // missing radius
// const d: Shape = { kind: "square", size: 2, radius: 1 }; // extra field on a fresh literal
const ok: Shape = { kind: "circle", radius: 1 };
console.log(ok.kind);The fourth error comes from excess property checking on fresh object literals. A value that already has extra properties and is assigned from another variable is not rejected. The type describes a minimum shape, not a closed one.
Design trade-offs
- Many variants versus one type with optional fields. Use a discriminated union when different cases have different required fields. Use a plain interface when the cases share the same fields.
- Tag name collisions. If your data comes from an API that already has a
typefield, reuse it as the discriminant instead of adding a second tag. - Changing tags later. Renaming a tag value is a breaking change for every
switchandifthat uses it. The compiler finds them all, which is one of the pattern's benefits.
Exercise
A teammate defines type Event = { type: string; id: number } | { type: string; message: string } and says it is a discriminated union. What is wrong, and how do you fix it?
Show answer
Both members declare type as string, which is not a unit type, so a check on type cannot tell the members apart. Give each member a distinct literal, for example { type: "click"; id: number } | { type: "message"; message: string }. After that, event.type === "click" narrows to the first member and event.id is a number.
Exercise
You need a union for a payment that is either a card payment with last4: string, or a bank transfer with iban: string. Both have an amount: number. Write the type.
Show answer
type Payment = { method: "card"; amount: number; last4: string } | { method: "bank"; amount: number; iban: string }; The shared amount is readable without narrowing, and method is the discriminant. You could also extract amount into a base interface and extend it in each member.