Skip to content
jshacks.dev
TypeScript

Discriminated Unions in TypeScript

Model values that can take several shapes with a shared tag property. Learn discriminated unions, narrowing by switch, error messages and modelling advice.

7 min read
Summarize in AI
Flat illustration of a log with a failing line and a wrench, with the TypeScript, JavaScript, npm and Vite logos.

Many values in a program come in a few distinct shapes. A payment can be pending, paid or failed, and each state carries different data. A network request is idle, loading, loaded with a result, or failed with an error. The natural way to model that in TypeScript is a discriminated union: a union of object types that share one property, the tag, whose value is a different literal in each member. Compare the tag and the compiler knows which member you hold, so only that member's properties are available. This post builds a discriminated union from scratch, shows the errors you get without one, covers narrowing with if and switch, and gives modelling advice and a testing approach. It uses TypeScript 6.x, and the pattern is described in the handbook chapter on narrowing.

The problem with one wide type

The first attempt at modelling variants is usually a single type with optional fields.

loose.tsTypeScript
type Payment = {
  status: "pending" | "paid" | "failed";
  receiptUrl?: string;
  failureReason?: string;
};

function describe(payment: Payment): string {
  if (payment.status === "paid") {
    return payment.receiptUrl.toUpperCase();
  }
  return "not paid";
}
Text
loose.ts(9,12): error TS18048: 'payment.receiptUrl' is possibly 'undefined'.

The compiler is right to complain, but the type is the real problem. It allows a payment with status paid and no receipt, and a payment with status pending and a failure reason. The type says nothing about which fields go with which status. Every reader of the code has to remember the rules, and the compiler cannot help. You can silence the error with !, and that is the moment the type system stops protecting you.

The same model as a discriminated union

Split the type into one member per status, and give each member exactly the fields that belong to it. The status property is the discriminant, and each member declares it as a distinct literal type.

payment.tsTypeScript
type Pending = { status: "pending" };
type Paid = { status: "paid"; receiptUrl: string };
type Failed = { status: "failed"; failureReason: string };

type Payment = Pending | Paid | Failed;

function describe(payment: Payment): string {
  if (payment.status === "paid") {
    return `receipt at ${payment.receiptUrl}`;
  }
  if (payment.status === "failed") {
    return `failed: ${payment.failureReason}`;
  }
  return "waiting for the bank";
}

console.log(describe({ status: "paid", receiptUrl: "https://example.test/r/1" }));
console.log(describe({ status: "failed", failureReason: "card declined" }));
console.log(describe({ status: "pending" }));
Text
receipt at https://example.test/r/1
failed: card declined
waiting for the bank

Inside the first if, the compiler narrows payment to Paid, because only that member has status: "paid". receiptUrl is a string there, not optional. Inside the second, it is Failed. After both returns, only Pending remains. The impossible combinations no longer type-check: a paid payment without a receipt is a compile error at the place where you build it.

impossible.tsTypeScript
type Paid = { status: "paid"; receiptUrl: string };

const payment: Paid = { status: "paid" };
Text
impossible.ts(3,7): error TS2741: Property 'receiptUrl' is missing in type '{ status: "paid"; }' but required in type 'Paid'.

The bug is reported where it is created, not where the value is later read, which is the most useful place for it.

What makes a property a discriminant

Not every shared property works. A discriminant must be present in every member, and its type in each member must be a unit type, such as a string literal, number literal, boolean literal, null or undefined, and the literals must differ between members. A plain string is not a discriminant because comparing it proves nothing about the other members.

not-a-tag.tsTypeScript
type Circle = { kind: string; radius: number };
type Square = { kind: string; side: number };

function area(shape: Circle | Square): number {
  if (shape.kind === "circle") {
    return Math.PI * shape.radius ** 2;
  }
  return shape.side ** 2;
}
Text
not-a-tag.ts(6,28): error TS2339: Property 'radius' does not exist on type 'Circle | Square'.
  Property 'radius' does not exist on type 'Square'.

Because both kind properties are string, the check on line 5 narrows nothing. Change them to kind: "circle" and kind: "square" and the same function compiles. Booleans work as tags too, as in { ok: true; value: T } | { ok: false; error: Error }, which is the shape of many result types.

Narrowing with switch

A switch on the discriminant is the idiomatic way to handle every member. Each case narrows the variable, and the layout reads as a table of the variants.

shapes.tsTypeScript
type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "rectangle"; width: number; height: number }
  | { kind: "triangle"; base: number; height: number };

function area(shape: Shape): number {
  switch (shape.kind) {
    case "circle":
      return Math.PI * shape.radius ** 2;
    case "rectangle":
      return shape.width * shape.height;
    case "triangle":
      return (shape.base * shape.height) / 2;
  }
}

console.log(area({ kind: "rectangle", width: 3, height: 4 }));
console.log(area({ kind: "triangle", base: 6, height: 5 }));
console.log(area({ kind: "circle", radius: 1 }).toFixed(4));
Text
12
15
3.1416

The function has no default and no return after the switch, and it still compiles, because the compiler sees that the three cases cover the union. If you add a fourth member, area fails to compile with TS2366 ("Function lacks ending return statement and return type does not include 'undefined'"), which points you at every function that needs a new case. The next post in this series, on exhaustiveness checking with never, makes that check explicit.

A result type with a boolean tag

A boolean works as a tag as well, which gives the common result type.

result.tsTypeScript
type Result<T> = { ok: true; value: T } | { ok: false; error: string };

function parsePort(text: string): Result<number> {
  const port = Number(text);
  if (!Number.isInteger(port) || port < 1 || port > 65535) {
    return { ok: false, error: `invalid port: ${text}` };
  }
  return { ok: true, value: port };
}

for (const text of ["8080", "http"]) {
  const result = parsePort(text);
  if (result.ok) {
    console.log(`port ${result.value}`);
  } else {
    console.log(result.error);
  }
}
Text
port 8080
invalid port: http

A result type like this is a lightweight alternative to exceptions where failure is an expected outcome. The caller has to look at ok before reaching the value, because value does not exist on the failing member, so the compiler enforces the error handling.

Real-world modelling advice

Model the states your program can actually be in, and make the others impossible to write. Three habits help.

Put the data with the state that owns it. A loading state needs no data, a loaded state has the data, and an error state has the error. Resist adding a data field to every member "just in case", since each such field recreates the optional-field problem.

Use one tag name across a codebase. Teams tend to settle on type, kind or status. Consistency lets a reader recognise the pattern and lets you write generic helpers.

Derive the tag type from the union, not from a second list. Payment["status"] gives "pending" | "paid" | "failed" and stays correct as members are added.

derive.tsTypeScript
type Payment =
  | { status: "pending" }
  | { status: "paid"; receiptUrl: string }
  | { status: "failed"; failureReason: string };

type Status = Payment["status"];

const labels: Record<Status, string> = {
  pending: "Pending",
  paid: "Paid",
  failed: "Failed",
};

console.log(labels.paid);
Text
Paid

Because the labels record is keyed by Status, adding a fourth status to the union makes this object a compile error until you add its label. The union drives every table that mirrors it.

Crossing a boundary

A discriminated union is a compile-time idea, so data coming from JSON arrives untyped. Check the tag at the boundary, with a type guard or a schema, and construct the union value only after the check. Casting parsed JSON with as Payment accepts a payload with a status of "paid" and no receipt, and the guarantee you built is gone. The guards post in this series shows how to write the check.

Testing a union-based function

Tests for such functions follow the structure of the type. Write one case per member, and add a case that pins the contract of the tag, for instance the label table above. The compiler already tests exhaustiveness, so the runtime tests focus on behaviour.

shapes.test.tsTypeScript
import { strictEqual } from "node:assert/strict";
import { area } from "./shapes.js";

strictEqual(area({ kind: "rectangle", width: 2, height: 5 }), 10);
strictEqual(area({ kind: "triangle", base: 4, height: 3 }), 6);
strictEqual(area({ kind: "circle", radius: 0 }), 0);

console.log("one case per variant passed");
Text
one case per variant passed

When a union is the wrong tool

If the variants differ in behaviour more than in data, and you expect to add new variants often, classes with a shared interface let you add a type without touching existing code. A discriminated union makes the opposite trade: adding an operation is easy, since it is one new function, and adding a variant touches every function that switches on the tag. Pick the one that matches the direction your code will grow. For data that is mostly the same with one or two optional fields, a single type with optional properties is simpler than a union.

Share

Keep reading

Flat illustration of an editor window full of code, with the TypeScript, npm and Node.js logos.
TypeScript

Type Inference in TypeScript

TypeScript works out most types for you. Learn how inference treats let and const, arrays, return values and callbacks, and when to write a type yourself.

7 min read
Flat illustration of an editor window full of code, with the TypeScript, Node.js, npm, Vite and JavaScript logos.
TypeScript

What Is TypeScript, and Why Use It?

TypeScript adds static types to JavaScript and checks them before your code runs. Learn what it is, what it catches, what it costs and when to use it.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.