Sub topic 8
Discriminated unions
This chapter assumes you know basic TypeScript syntax, type aliases, union types such as string | number, and switch statements. It also assumes you have seen typeof, in, and equality checks narrow a value. Here you will learn how to design a union so the compiler narrows it with one cheap check.
The problem with plain object unions
Suppose you model the result of a network call. A first attempt often looks like this:
type Result = {
ok: boolean;
value?: string;
error?: string;
};
function describe(result: Result): string {
if (result.ok) {
// value is still string | undefined here
return result.value.toUpperCase();
}
return result.error.toUpperCase();
}With strictNullChecks on, both result.value and result.error are reported as possibly undefined. The type allows impossible states, such as ok: true with no value. The compiler cannot know that ok and value are linked, because you never told it.
A union of separate object types can express the link. Each member lists exactly the properties that exist in that state.
What makes a union discriminated
A discriminated union (also called a tagged union) is a union of object types where every member has a common property with a distinct literal type. That property is the discriminant.
type Result =
| { status: "success"; value: string }
| { status: "failure"; error: Error };
function describe(result: Result): string {
if (result.status === "success") {
return result.value.toUpperCase();
}
return result.error.message;
}Checking result.status === "success" is an equality check on a property. TypeScript removes every union member whose status type cannot be "success". Inside the if, result is the success member. After the early return, only the failure member is left, so result.error is valid.
Three requirements define a discriminant:
- The property exists on every member of the union.
- Its type on each member is a literal type, such as a string literal, a number literal, a boolean literal,
null, orundefined. - The literal types differ between members, so a value of one literal identifies one member.
The diagram below shows how the checks split the union.
Narrowing with switch
A switch on the discriminant is the usual way to handle more than two members. Each case narrows the value in its own block.
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;
}
}Because every member is covered and each branch returns, TypeScript accepts the function without a final return. If you later add a fourth member and forget to handle it, the compiler reports that the function can end without returning a value. The next chapter turns this into an explicit check with never.
You can also group cases that share behavior. Inside a grouped case the value is narrowed to the union of the listed members.
type Event =
| { type: "click"; x: number; y: number }
| { type: "keydown"; key: string }
| { type: "keyup"; key: string };
function keyOf(event: Event): string | undefined {
switch (event.type) {
case "keydown":
case "keyup":
return event.key; // narrowed to the keydown | keyup members
case "click":
return undefined;
}
}Choosing a discriminant
Any common property with literal types works. These are the usual choices.
| Discriminant type | Example | Notes |
|---|---|---|
| String literal | `kind: "circle"` | Most common. Easy to read in logs and JSON. |
| Number literal | `code: 200` | Works, but the meaning of the number is less obvious. |
| Boolean literal | `ok: true` / `ok: false` | Good for two states only. |
| `null` or `undefined` | `error: null` vs `error: Error` | Works because `null` is a unit type, but it reads less clearly. |
The name is a convention, not a rule. kind, type, tag, and status are common. Pick one name and use it across related unions so readers know where to look.
Boolean discriminants deserve a small example, because they let you replace the broken Result type from the start of the chapter.
type Outcome =
| { ok: true; value: number }
| { ok: false; reason: string };
function unwrap(outcome: Outcome): number {
if (outcome.ok) {
return outcome.value;
}
throw new Error(outcome.reason);
}Narrowing by destructuring
You can destructure the discriminant together with the other properties, and TypeScript still tracks the relationship. This works for destructured const bindings and parameters, from TypeScript 4.6 onward.
type Action =
| { type: "add"; amount: number }
| { type: "reset" };
function apply(total: number, action: Action): number {
const { type } = action;
if (type === "add") {
return total + action.amount;
}
return 0;
}Here type is a const copy of action.type, and the check on it narrows action. The copy must be a const or a parameter that is never reassigned.
Common mistakes
The property is not a literal type
If the tag is typed as string, no member can be excluded, so no narrowing happens.
type Broken =
| { kind: string; radius: number }
| { kind: string; size: number };
function broken(shape: Broken): number {
if (shape.kind === "circle") {
return shape.radius; // error: Property 'radius' does not exist on type 'Broken'
}
return 0;
}This often happens when an object is built without as const or a type annotation. A value such as { kind: "circle", radius: 2 } assigned to a mutable variable infers kind: string.
type Circle = { kind: "circle"; radius: number };
type Square = { kind: "square"; size: number };
type Shape = Circle | Square;
const inferred = { kind: "circle", radius: 2 };
// inferred.kind is string, so this assignment is an error
// const bad: Shape = inferred;
const annotated: Shape = { kind: "circle", radius: 2 }; // kind stays "circle"
const frozen = { kind: "circle", radius: 2 } as const; // kind is "circle"Overlapping tags
If two members share the same literal, a check cannot tell them apart. The narrowed type is then the union of both members.
Optional discriminants
A discriminant declared as kind?: "a" includes undefined. Checks still work, but the member with the optional tag overlaps with any member whose tag is undefined. Make the tag required.
Testing a different property than the tag
Checking "radius" in shape narrows too, as the earlier chapter on in showed, but it breaks when two members share a property name. A real discriminant keeps working when you add members that have overlapping fields.
Comparing with the wrong operator
Use ===. A == comparison with a literal also narrows, but strict equality is the convention and avoids coercion surprises.
Discriminated unions and generics
Generic types can carry a discriminant too. A reusable Result type is a typical case.
type Result<T, E = Error> =
| { ok: true; value: T }
| { ok: false; error: E };
function parsePort(text: string): Result<number, string> {
const port = Number(text);
if (!Number.isInteger(port) || port < 1 || port > 65535) {
return { ok: false, error: `Invalid port: ${text}` };
}
return { ok: true, value: port };
}
const parsed = parsePort("8080");
if (parsed.ok) {
console.log(parsed.value + 1);
} else {
console.log(parsed.error.toUpperCase());
}The returned object literals are checked against the declared return type, so ok: true stays the literal true and does not widen to boolean.
Design guidelines
- Put the shared discriminant first in each member so the shape of the union is easy to scan.
- Include only the properties that are valid in that state. If a property is meaningless in a state, leave it out of that member.
- Keep properties that every member shares, such as
id, in a common base type and combine it with an intersection, as inBase & ({ kind: "a" } | { kind: "b" }). - Prefer a discriminated union over optional properties whenever several properties are present or absent together.
- When data crosses a trust boundary, such as JSON from a server, the type is a claim and not a check. Validate the tag at runtime before treating the value as a member of the union. A later chapter covers this.
Exercises
Exercise
A function receives type Msg = { t: "text"; body: string } | { t: "image"; url: string; alt?: string }. Write a function summary(msg: Msg): string that returns the body for text messages and the url for image messages, using a switch on the discriminant.
Show answer
```typescript is not allowed inside this answer, so here it is in plain form: function summary(msg: Msg): string { switch (msg.t) { case "text": return msg.body; case "image": return msg.url; } }. The discriminant is t, and each case narrows msg to one member, so body and url are both accessible without extra checks.
Exercise
Why does type Bad = { kind: string; a: number } | { kind: string; b: number } fail to narrow when you write if (x.kind === "a")?
Show answer
The kind property has type string in both members, which is not a literal type. Comparing a string with "a" cannot rule out either member, so x stays Bad and the properties a and b are not accessible. Changing the types to kind: "a" and kind: "b" makes kind a discriminant.