Discriminated Unions in TypeScript, with Examples
One shared literal field such as kind or status tells every variant apart. The pattern behind API results, Redux actions and state machines.
In this chapter
Discriminated unions
Discriminated unions: common questions
What is a discriminated union?
A union whose members share one literal property, for example status: "loading" | "success" | "error". Checking that property narrows to the matching member.
More on Unions and narrowing
Keep learning
Overview
Value of state.status error: does not exist here chapters · unions and narrowing Discriminated unions One shared literal field tells every variant apart. The pattern behind API results, actions and state machines. A union (A | B | C) means "one of these types". Each type in it is a variant. A literal type allows one exact value, like 'success'.
1. The problem: a bag of optional fields
Order history can be loading, loaded, or failed. The first try puts every field in one type. one type, everything optional 'state.orders' is possibly 'undefined'. The ? means "this field may be missing". Line 8 fails: TypeScript sees three unrelated fields. Knowing loading and error are off tells it nothing about orders. The type also allows nonsense: loading: true with an error AND orders. one variant per state orders: Order[] Impossible states cannot be written. On line 6, only the 'success' variant has that status. So inside the if, state is that variant, and orders must exist. combinations the bag allows (loading true/false × orders there/missing × error there/missing) states that really exist
2. Anatomy: the three parts
Same field name every variant has status (or kind, type) Literal value 'success', not string: that is what tells them apart Own extra fields each variant carries only what it needs The shared field is the discriminant (the tag that says which variant). Click a tag to narrow.
What is left of state.status after each case
before the switch 'loading' | 'success' | 'error' after case 'loading' returns 'success' | 'error' after case 'success' returns after case 'error' returns never is the empty type: no value fits it. Reaching never means no status is left over, so every case is handled. See exhaustiveness checks.
4. API results
A fetch either works or fails. Model both, and the caller cannot skip the error path. ApiResult<T> is generic: T is a placeholder type, filled in later. Here T becomes Dish[]. Line 8 fails: res might be the error variant, which has no data. Line 9 works because the check proves it is the 'ok' variant. tag from destructuring destructure both
5. Actions and reducers
text: string messageId: string dispatch takes a ChatAction. Does this compile?
6. State machines
A state machine is a thing that is always in exactly one step and moves between steps by rules. A table booking moves through steps. Each step has its own data, and only legal fields exist. date?, seats? tableId, expiresAt tableId, code no table only a 'holding' booking can be confirmed must be both
Remember
Give every variant one shared field with a literal value. Checking that field narrows the whole object. Unions of variants beat one type with many optional fields. Use it for API results, reducer actions and multi-step flows. The tag must stay a literal: watch for widening to string. Destructured tags still narrow, as long as nothing is reassigned. ! Cheat code → Go deeper: exhaustiveness checks with never, unions and literal types, when narrowing is lost, 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.