TypeScript · Narrowing and unions

Exhaustive switch

A never assignment in the default branch makes the compiler flag any unhandled union member.

Syntax
const _never: never = value

Example

Example
type Status = "draft" | "published";
function label(status: Status) {
  switch (status) {
    case "draft": return "Draft";
    case "published": return "Published";
    default: { const _never: never = status; return _never; }
  }
}

More in this group

Assertion function Discriminated union in operator instanceof guard Non-null assertion Type assertion Type predicate typeof guard

Learn this in the course

Reference pages are the quick answer. The course explains the why, shows the full example and ends with a challenge.

Open the course