BeginnerCoder

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.

Want it another way?
Task

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.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.

Keep going with TypeScript Foundations

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.