Lesson 1.2

Unions and narrowing

A discriminated union plus a check on the discriminant is the workhorse pattern of typed application code. Narrowing is how the compiler follows your control flow.

10mIntermediate20,968 students
Video thumbnail for Unions and narrowing

Sign in to watch this lesson

Browsing is free. Create an account to play videos and track your progress.

Overview

A discriminated union plus a check on the discriminant is the workhorse pattern of typed application code. Narrowing is how the compiler follows your control flow.

What this lesson covers

  • Model alternatives as a discriminated union
  • Narrow with typeof, in, and discriminant checks
  • Make a switch exhaustive with a never assertion

This lesson sits in How the Type System Thinks, part of TypeScript for Application Developers. It assumes what came before it and leads directly into the next lesson in the module.

In this lesson you will:

  • Model alternatives as a discriminated union
  • Narrow with typeof, in, and discriminant checks
  • Make a switch exhaustive with a never assertion

Pro Tip

An exhaustive switch that assigns the leftover case to never turns a future missing branch into a compile error.

Unions and narrowing — Skiply