Sub topic 4
Choosing a discriminant property
This chapter assumes you know basic TypeScript types and unions, you can write if and switch statements, and strict: true is on in your tsconfig.json. It covers which property can act as the tag of a discriminated union and how to choose one that works well.
What a discriminant does
A discriminated union is a union of object types that share one property, the discriminant. TypeScript reads that property to decide which member you are holding. When you write event.type === "click", the compiler removes every member whose type cannot be "click". Inside the branch, only the matching member is left.
type AppEvent =
| { type: "click"; x: number; y: number }
| { type: "keypress"; key: string }
| { type: "resize"; width: number; height: number };
function log(event: AppEvent): string {
if (event.type === "click") {
return `click at ${event.x},${event.y}`;
}
if (event.type === "keypress") {
return `key ${event.key}`;
}
return `resize ${event.width}x${event.height}`;
}
console.log(log({ type: "keypress", key: "a" }));This only works if the property meets certain rules. The sections below cover them.
The four requirements
A property is a usable discriminant when it satisfies all of these:
- Every member declares it. If one member lacks the property, reading it on the union is an error, and the check cannot separate that member from the others.
- Its type is a unit type in at least one member. A unit type has exactly one possible value, such as
"click",42,true,null, orundefined. The typestringis not a unit type. - The values separate the members. Checking one value should leave the members you expect. Members can share a value, but then the check cannot tell them apart.
- The value is known at compile time. The compiler must see a literal type, not a widened one. The pitfalls chapter covers widening in detail.
Which types can serve as a tag
| Tag type | Example | Typical use |
|---|---|---|
| String literal | `kind: "circle"` | Most common. Readable and survives JSON. |
| Number literal | `version: 2` | Versioned data formats. |
| Boolean literal | `ok: true` | Two-variant unions such as `Result`. |
| `null` | `error: null` | One variant has no value. |
| `undefined` | `error?: undefined` | Optional marker property. |
| Enum member | `kind: Kind.Circle` | Codebases that already use enums. |
String literals are the default choice. They are readable in debuggers and logs, and they serialize to JSON without changes. Enums add a runtime object and a separate import, and a plain string such as "circle" from parsed JSON is not assignable to an enum type.
Here is a number literal tag used for versioned records:
type UserRecord =
| { version: 1; name: string }
| { version: 2; firstName: string; lastName: string };
function displayName(user: UserRecord): string {
if (user.version === 1) {
return user.name;
}
return `${user.firstName} ${user.lastName}`;
}
console.log(displayName({ version: 2, firstName: "Ada", lastName: "Lovelace" }));Choosing a good property name
TypeScript does not care what you call the discriminant. Your team and your data do, so consider these points:
- Pick one name and use it everywhere.
kind,type,tag, andstatusare common. Many codebases usetypefor events and actions,kindfor syntax trees and shapes, andstatusfor request state. - Avoid names that collide with real data. If members carry a domain field called
type, such as a product type, a tag also calledtypeis confusing. Usekindfor the tag instead. - Match the wire format when you can. If a server already sends
"type": "click", using the same property saves a translation step. - Name the tag for what it answers.
statussuits "where is this request?", andkindsuits "which variety of thing is this?".
Choosing the tag values
Each value should describe its variant, not its position. Prefer "loading" over "state2". Keep the casing consistent, because "Circle" and "circle" are different types and a typo in one place fails to match.
The values also need to be unique per variant where you want them to separate. Look at this union:
type Field =
| { kind: "text" | "email"; value: string }
| { kind: "number"; value: number };
function show(field: Field): string {
if (field.kind === "number") {
return (field.value * 2).toString();
}
return field.value.toUpperCase();
}
console.log(show({ kind: "email", value: "[email protected]" }));One member can accept several tag values. That works here because "text" and "email" share a payload, and the check against "number" still separates the two members cleanly. What you should avoid is the same value appearing in two members, as in { kind: "a"; x: number } | { kind: "a"; y: string }. After kind === "a" both members remain, so x is not available.
A decision path
The flowchart below summarizes how to pick a tag for a new union.
When the type is not a literal
The most common failure is a tag typed as string. The compiler then has nothing to compare, so the union does not narrow.
type BadShape =
| { kind: string; radius: number }
| { kind: string; size: number };
function badArea(shape: BadShape): number {
if (shape.kind === "circle") {
// Error: Property 'radius' does not exist on type
// '{ kind: string; size: number; }'.
return Math.PI * shape.radius ** 2;
}
return 0;
}shape.kind === "circle" is valid code, but it tells the compiler nothing, because any string could be a circle. Replacing string with "circle" and "square" fixes it.
type GoodShape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number };
function goodArea(shape: GoodShape): number {
if (shape.kind === "circle") {
return Math.PI * shape.radius ** 2;
}
return shape.size ** 2;
}
console.log(goodArea({ kind: "square", size: 4 }));`null` and `undefined` as discriminants
Since TypeScript 3.2, null and undefined count as unit types, so a property that is undefined in one member and a real type in another can discriminate.
type Outcome =
| { data: string; error?: undefined }
| { data?: undefined; error: Error };
function render(outcome: Outcome): string {
if (outcome.error !== undefined) {
return `Failed: ${outcome.error.message}`;
}
return `Got: ${outcome.data}`;
}
console.log(render({ data: "ok" }));
console.log(render({ error: new Error("boom") }));This shape is common in code that predates discriminated unions, and it is worth recognizing. For new code, an explicit tag is clearer. A reader sees status: "error" at a glance, but has to work out that error !== undefined is the signal in the example above.
Edge cases
- Optional tags.
kind?: "a"has the type"a" | undefined. It still narrows, but you must handle theundefinedcase, which usually means one member is untagged. Prefer a required tag. - A tag that is a union within one member.
kind: "a" | "b"is allowed. After a check against"a", TypeScript keeps that member, and the property is narrowed to"a"within the branch. - Nested tags. If the tag lives at
shape.meta.kind, checking it does not narrowshape. Narrowing works on the property of the object you are testing, so keep the tag at the top level of each member. - Destructuring. Destructuring a tag and a payload together, as in
const { kind, radius } = shape, only narrows reliably in recent TypeScript versions and under conditions such asconstbindings. If it does not narrow, testshape.kinddirectly. - Two tags. You can use two discriminants, such as
categoryandtype, and narrow in two steps. Keep this rare, because each extra layer is another place for a mismatch.
Summary of rules
- Use a required property with the same name in every member.
- Give it a literal type, usually a string literal.
- Make the values describe the variants, and keep them unique where narrowing must separate members.
- Keep the tag at the top level of each member.
- Pick a name that does not collide with domain data.
Exercise
This union does not narrow. Why, and how do you fix it?
type Message =
| { type: string; text: string }
| { type: string; url: string; width: number };
function describe(m: Message): string {
if (m.type === "image") {
return ${m.url} (${m.width}px);
}
return m.text;
}
Show answer
The tag type is typed as string in both members, so m.type === "image" does not remove either member, and m.url is an error. Give each member a literal type: { type: "text"; text: string } | { type: "image"; url: string; width: number }. After that, m.type === "image" narrows m to the image member, and the fallthrough return is the text member.
Exercise
A teammate proposes { kind: "a"; x: number } | { kind: "a"; y: string }. Does kind work as a discriminant? What would you change?
Show answer
No. Both members use the same value "a", so a check against "a" leaves both members and x and y stay unavailable. Give each variant its own value, for example "point" and "label", so each check selects exactly one member.