Exhaustive Switch in TypeScript with never
Make the compiler fail when a new union member is added and a switch forgets it, using an assertNever helper or satisfies never.
In this chapter
Exhaustiveness checks with never
More on Unions and narrowing
Keep learning
Overview
Change the union backend sends 'refunded' ✓ add 'refunded' to Status Cases handled in the switch Every case handled: s is never in default. Compiles. chapters · unions and narrowing Exhaustiveness checks with never Make the compiler fail when someone adds a new case and forgets to handle it.
1. The problem: a new status, a blank badge
The backend adds 'refunded'. Someone updates the type. Nothing else fails to compile. Words used below: a union like 'pending' | 'paid' means “one of these values”. A literal type like 'paid' allows exactly that one string. never is the empty type: no value at all fits into it. Both sides below use the same 3-member union. The left switch handles 2 cases. The right one adds a check in default. no exhaustiveness check returns string | undefined with a never check Type 'string' is not assignable to type 'never'. s: 'refunded' In default, s can only be 'refunded' (the case nobody handled). Putting 'refunded' into a never box does not fit, so the build fails at this exact switch.
2. never: the type with no values
No value fits nothing is assignable to never (except never) Left after every case a union with all members removed is never So assigning is a test if anything is left, the assignment errors
What s can still be, case by case
entering the switch 'pending' | 'paid' | 'refunded' after case 'pending' 'paid' | 'refunded' after case 'paid' in default: forgot one add case 'refunded' Why does the message say 'string', not 'refunded'? When it prints the error, TypeScript widens the literal (turns 'refunded' into its general type string). The real leftover is still 'refunded'. Read “is not assignable to type 'never'” as “a value is left over that no case handled”.
3. Try it: break the build on purpose
Add the new status, untick cases, and watch the default branch. assertNever(s) is a helper that only accepts a never argument (section 4 shows it). The grey hint shows what s can still be in default. Any leftover value means a red error.
4. Four ways to write the check
never variable Type 'string' is not assignable to type 'never'. No helper needed. Storing s in a never variable fails if any value is left. The underscore says “unused on purpose”. satisfies never Type 'string' does not satisfy the expected type 'never'. checks that x fits T without changing its type. One line, no unused variable (TS 4.9+). Argument of type 'string' is not assignable to parameter of type 'never'. The parameter type never means: only call me when nothing is left. You get a compile error, AND a runtime throw if the server sends something new anyway.
5. Lookup tables: Record<Union, …>
Often you do not need a switch at all. Record<K, V> is a built-in type: an object with every key from K, each holding a V. So a Record keyed by the union must list every key. Plain cause: the type demands 3 keys, the object has 2. The missing key is named in the message. catches a new member? switch, no default default + never check Record<Status, T> best for pure value lookups Partial<Record<Status, T>> Partial makes every key optional, so a missing key is allowed
6. Types check your code, not the server
Compile time never catches cases your code forgot after you update the type. Run time
Remember
never has no values, so nothing can be assigned to it. After every case is handled, the variable is never. A catch-all default without the check hides new cases. Record<Union, T> forces every key in lookup tables. assertNever also throws at runtime for surprise values. ! Cheat code → Go deeper: discriminated unions, unions and literal types, interview: the new status nobody handled.
More courses
- Jobs, linked to lessons — Browse jobs where every requirement links to the chapter that teaches it. See how ready you are, how long the gap takes to close, and which listings look stale.
- Match a job post to courses — Paste a job post. Each skill is matched to a track here and put in learning order, foundations first.
- React patterns from open source — Patterns extracted from Material UI, Radix, React Aria, React Hook Form, Redux Toolkit, TanStack, and Next.js — not slides about hooks.
- Databases in depth — How a query becomes work. Indexes, isolation, locks, and the plans that explain why a page is slow — not an ORM tour.
- System Design — Core concepts first (SQL vs NoSQL, CAP, indexing, replication, sharding), then designs grouped by what carries them: the database, Redis, Kafka, or many services.
- NestJS: build a real API — One ticket-booking API, built in order: a plain Node server first, then NestJS modules, validation, a real database, and the features real clients lean on.
- Microservices — Microservice patterns one diagram at a time: how to split a monolith, how services talk, and how data stays consistent without distributed transactions.
- Kafka — A beginner-to-senior path through event logs, reliable delivery, production operations, and disaster recovery.
- AI engineering for software engineers — Eight free reads, in order, for software engineers moving into AI: when to build an agent, how to build one, how to test it, and how the model works underneath.
- Frontend system design — How a UI is sliced when it is a product, not a page: ownership of state, cache, routes, and what happens when the network lies.
- CSS in depth — See the box, then the page. Visual chapters from the box model through Flexbox surprises, Grid, selectors, and units, then backgrounds, shapes, and visual effects, each with a playground.
- Accessibility — Foundations first (WCAG in plain words, semantic HTML, lists, alt text), then hands-on HTML labs, a full pass of WAI-ARIA 1.3, and a final fix-the-page challenge.
- Docker — What an image is, why layers cache, and how containers find each other on a network.
- Redis — Fifteen Redis patterns, one picture each: cache, session, lock, counter, rate limiter, queue, and when Redis is the wrong tool.
- Kubernetes — Kubernetes from zero to operators: why it exists, Pods, Deployments and Services, then configuration, networking, storage, scheduling, scaling and security.
- AWS — AWS networking in plain English. A VPC is a gated housing society: streets are subnets, the Internet Gateway is the main gate, and a route table is the signboard.
- Networking: the NetRoute game — NetRoute is a packet logistics game. You wire up computers, switches, routers, firewalls and gateways, set each device, and watch glowing packets travel. If a packet gets dropped, the game shows you which header field was wrong.