Discriminated Unions
A discriminated union is a union of object types that all carry the same property, where that property holds a different literal value in each member. Checking that one property tells the compiler exactly which member you are holding.
Detailed Explanation
Say you are typing the result of a card charge. It either succeeded with a transaction id, or it failed with an error code. A first attempt usually looks like one object with everything optional:
type Charge = { ok: boolean; txnId?: string; errorCode?: string };
This type lies. It permits { ok: true, errorCode: "declined" }, which cannot happen. And every time you read txnId, the compiler hands you string | undefined, so you write a null check that you already know is unnecessary. The type has lost the connection between ok and the fields that go with it.
A discriminated union keeps that connection. You write each real case as its own object type, then union them:
type Charge =
| { status: "succeeded"; txnId: string }
| { status: "declined"; errorCode: string };
status is the discriminant (also called the tag). Impossible combinations are now unrepresentable. There is no way to build a value with status: "succeeded" and an errorCode.
The payoff is narrowing. When you test the discriminant, TypeScript's control-flow analysis removes the union members that cannot match, and inside that branch the value has one concrete type with no optional fields. This happens with switch, with if (c.status === "declined"), and with ternaries. The compiler is not running your code; it is reading the comparison and reasoning about which literal types could still be true.
Three conditions have to hold for this to work:
| Requirement | Why |
|---|---|
| The discriminant exists on every member | The compiler must be able to read it before it knows which member you have |
| Its type is a literal type in each member | string matches everything, so status: string discriminates nothing |
You compare it with ===, switch, or a literal equality check | Narrowing keys off the comparison, not off your intent |
Some near-misses still work. A boolean discriminant is fine, because true and false are literal types. An enum member is fine. Narrowing also survives destructuring, as long as you destructure the discriminant and the payload in the same statement — that landed in TypeScript 4.6.
The costs are small but real. You write more type declarations than the optional-field version, and adding a new case means touching every switch. That last one is usually a feature: pair it with an exhaustiveness check and the compiler lists the places you forgot. What you get in return is that the type stops describing a shape and starts describing a set of possible states.
Code Examples
1. The mechanic: one shared literal property, narrowed by a switch.
// 1. The mechanic: one shared literal property, narrowed by a switch.
type Charge =
| { status: "succeeded"; txnId: string }
| { status: "declined"; errorCode: string }
| { status: "pending"; retryAfterMs: number };
function describe(charge: Charge): string {
switch (charge.status) {
case "succeeded":
return `Paid, receipt ${charge.txnId}`; // charge is the succeeded member here
case "declined":
return `Card declined (${charge.errorCode})`;
case "pending":
return `Retry in ${charge.retryAfterMs}ms`;
}
}
const c: Charge = { status: "declined", errorCode: "insufficient_funds" };
console.log(describe(c)); // "Card declined (insufficient_funds)"2. Why it beats a bag of optional fields.
// 2. Why it beats a bag of optional fields.
type Loose = { ok: boolean; txnId?: string; errorCode?: string };
const impossible: Loose = { ok: true, errorCode: "declined" }; // allowed, and wrong
function readId(r: Loose) {
return r.txnId.slice(0, 8);
// Error: 'r.txnId' is possibly 'undefined'.
// Checking r.ok does not help: the compiler sees no link between ok and txnId.
}3. The discriminant must be a literal type, and you must actually test it.
// 3. The discriminant must be a literal type, and you must actually test it.
type Bad =
| { kind: string; radius: number } // 'string', not a literal
| { kind: string; side: number };
declare const shape: Bad;
if (shape.kind === "circle") {
shape.radius;
// Error: Property 'radius' does not exist on type 'Bad'.
// Nothing was eliminated, because "circle" does not rule out either member.
}
// Destructuring keeps the narrowing (TypeScript 4.6+), if done in one statement:
declare const charge: { status: "ok"; txnId: string } | { status: "err"; code: number };
const { status, ...rest } = charge;
if (status === "ok") {
// rest is { txnId: string }
}Common Gotchas
A widened discriminant discriminates nothing
if the tag is typed `string` instead of a literal, or a `let` binding widened it, every comparison narrows to the full union. Declare tags as literal types, and use `as const` when the values come from an object literal.
Narrowing is forgotten across a callback or an `await`
the compiler discards a narrowing when the value could have changed in between, and it cannot see inside a closure it does not control. Pull the narrowed value into a `const` inside the branch and use that.
Two members may share a discriminant value only if you never need to tell them apart
duplicating `status: "error"` across two members leaves you with a union inside the branch, not a single type. Give each real case its own tag value.
`in` checks are a weaker substitute
`if ("txnId" in charge)` narrows, but it depends on a payload field rather than a declared tag, so renaming that field silently changes which branch runs the checks. Prefer testing the discriminant.