TypeScript Foundations·Types that pay for themselves

Unions and narrowing

Model uncertain states explicitly and let the compiler prove which branch is safe.

Intermediate 14 min read Lesson 8 of 300 Challenge included
What you will be able to do
  • Discriminated unions use a shared literal field such as kind or status.
  • Never cast with as to silence an error you do not understand.
  • Exhaustive switch statements turn future additions into compile-time reminders.

In plain English

A union says a value may be one of several types. Narrowing uses runtime checks such as typeof, in and equality to reduce that union. The compiler follows your checks, so impossible states become hard to represent.

result.tsTypeScript
type Result =
  | { status: 'valid'; score: number }
  | { status: 'revoked'; reason: string }

function describe(result: Result): string {
  if (result.status === 'valid') {
    return 'Score: ' + result.score
  }
  return 'Revoked: ' + result.reason
}
Your turn

Handle a loading state

Medium

Model a state union with loading, ready and error variants. Write a function that returns a user-facing label for each.

TS · starter
type State = unknown

function label(state: State): string {
  return ''
}
Check your understanding before moving on.
Knowledge checkQuestion 1

Why is status: "valid" | "revoked" useful in a union?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Lesson 8 of 300 · 0% of course