Modeling Real Application Data

Unions and narrowing

Represent several allowed states and safely discover the current one.

8 minutes - Absolute beginner

What this means

A union allows more than one type. Narrowing uses checks such as typeof, in, equality, or a discriminant property to prove which union member is present.

In beginner terms, this topic answers one practical question: "What should I write, and why does React care about it?" Do not try to memorize the syntax first. First understand the idea, then connect the syntax to that idea.

Why it matters

Loading, success, and error states should be modeled so impossible combinations cannot appear.

When you build real React screens, this idea helps you decide where data should live, what the user should see, and what should happen after an interaction. That is why this lesson is part of the main path instead of being an optional detail.

Step by step

1. Notice the UI problem this topic solves. 2. Look at the smallest possible example. 3. Change one value and predict what should appear. 4. Run the example and compare the result with your prediction. 5. Use the practice task before moving on.

Small example

type Result = { status: "success"; data: string } | { status: "error"; message: string };

Common mistake

Do not access properties that exist on only one union member before narrowing the value.

Practice task

Model loading, success, and error states with a discriminated union and render one state.

Remember this

Narrow before using member-specific data.

try.it

Examples

Try it: Unions and narrowing

Edit this focused TypeScript example and run it in the browser preview.

Preview runs React in a sandboxed browser frame, never on the server.

typescript

editor

preview

Preparing preview...

practice.next

Practice before moving on

check.understanding

Lesson quiz

Login to save progress

You can read lessons without an account, but progress requires login.

Login