Lesson 18 — Discriminated unions
Unions with a tag
A discriminated union gives every shape a shared field with a fixed text value — a tag, such as kind: "circle" or kind: "square". Checking the tag (often with switch) tells TypeScript exactly which shape you have, so it lets you use that shape's own fields.
type Msg = { kind: "text"; body: string } | { kind: "image"; url: string };
function show(m: Msg) {
return m.kind === "text" ? m.body : m.url;
}
Why it matters: this is the standard way to model events, API results and app state that can be in several forms.
Switch on s.kind to return the right area: square side 4 → 16, circle r 2 → 12.56.
Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.
A quick 3-question quiz on this lesson — instant feedback.
Ready for more? Optional paid resources that pick up where this lesson leaves off.
Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.
Project-based TypeScript Foundations courses if you want a structured paid path after the free lessons. Wait for a sale — prices drop often.
Browse on Udemy →Search Amazon for TypeScript Foundations books — check the publication year so the examples match current versions.
Search Amazon →