Building Discriminated Unions
Tag union members with a shared discriminant property.
Building Discriminated Unions is a free TypeScript Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the TypeScript Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What Is a Discriminated Union?
A discriminated union is a union of object types that all share a common literal property called the discriminant. That shared tag lets TypeScript tell the members apart.
// The shared "kind" property is the discriminant
type Circle = { kind: "circle"; radius: number };
type Square = { kind: "square"; side: number };
type Shape = Circle | Square;The Discriminant Property
The discriminant must be a literal type (like "circle"), not a wide type like string. Each member gets its own unique literal value.
type Circle = { kind: "circle"; radius: number };
type Square = { kind: "square"; side: number };
const c: Circle = { kind: "circle", radius: 10 };
console.log(c.kind); // "circle"Each Member Has Its Own Fields
Beyond the shared discriminant, every member carries the fields that only make sense for it. A circle has a radius; a square has a side.
type Circle = { kind: "circle"; radius: number };
type Square = { kind: "square"; side: number };
type Rectangle = { kind: "rectangle"; width: number; height: number };
type Shape = Circle | Square | Rectangle;Constructing Union Values
When you build a value, TypeScript checks that the shape matches exactly one member of the union based on its kind.
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; side: number };
const shapes: Shape[] = [
{ kind: "circle", radius: 5 },
{ kind: "square", side: 4 }
];
console.log(shapes.length); // 2Why Not Just Optional Fields?
A loose type with optional fields (radius?, side?) allows invalid combinations. The discriminated union makes illegal states unrepresentable.
// Loose and error-prone: nothing stops radius + side together
type BadShape = { radius?: number; side?: number };
const bad: BadShape = { radius: 5, side: 4 }; // nonsense, but allowedThe Discriminant Name Is Up to You
The tag is conventionally called kind or type, but any name works as long as every member uses the same property name with a distinct literal value.
type Event =
| { type: "click"; x: number; y: number }
| { type: "scroll"; delta: number };
const e: Event = { type: "click", x: 10, y: 20 };
console.log(e.type); // "click"Modeling a Shape Area Calculator
Discriminated unions shine when each variant needs different handling. Here we set up shapes that an area function will later process.
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; side: number };
const myShapes: Shape[] = [
{ kind: "circle", radius: 3 },
{ kind: "square", side: 6 }
];
console.log("Count:", myShapes.length);Adding a Third Variant
Unions are open to extension. Adding a triangle member is a one-line change, and TypeScript will track it everywhere the union is used.
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; side: number }
| { kind: "triangle"; base: number; height: number };
const t: Shape = { kind: "triangle", base: 4, height: 8 };
console.log(t.kind);Unique Literals Prevent Overlap
Because each kind is unique, there is no ambiguity. A value is exactly one member, never two at once.
type A = { kind: "a"; value: number };
type B = { kind: "b"; label: string };
type Union = A | B;
function describe(u: Union) {
return u.kind === "a" ? u.value : u.label;
}
console.log(describe({ kind: "b", label: "hi" }));Discriminants With Boolean Tags
The discriminant does not have to be a string. A boolean literal works too, which is handy for success/failure results.
type Result =
| { ok: true; data: string }
| { ok: false; error: string };
const r: Result = { ok: true, data: "loaded" };
console.log(r.ok ? r.data : r.error);Discriminated Unions in Practice
You now have a complete shape model. In the next lesson we will narrow on the discriminant to safely access each member specific field.
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; side: number };
const sample: Shape = { kind: "circle", radius: 7 };
console.log(sample.kind, "ready");Quick Check: Discriminants
Test your understanding of discriminated unions.
Recap: Building Discriminated Unions
You learned that a discriminated union joins object types that share a literal discriminant like kind. Each member carries its own fields, unique literals prevent overlap, and the pattern makes illegal states unrepresentable.
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; side: number };
const done: Shape = { kind: "square", side: 2 };
console.log("Recap complete:", done.kind);Frequently asked questions
Is the “Building Discriminated Unions” lesson free?
Yes — the full text of “Building Discriminated Unions” is free to read here on the web, and the TypeScript Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the TypeScript Academy course, upgrade to CoddyKit PRO.
What will I learn in “Building Discriminated Unions”?
Tag union members with a shared discriminant property. You practise TypeScript Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start TypeScript Academy?
No prior experience is required. TypeScript Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Building Discriminated Unions” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this TypeScript Academy lesson?
Yes. Every TypeScript Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Building Discriminated Unions
- Narrowing on the Discriminant
- Exhaustiveness Checking with never
- Modeling State Machines