Discriminated state in real libraries
Query status, Redux actions and state machines: one field decides which other fields exist. A free TypeScript lesson with examples.
More on Patterns from open source
Keep learning
Overview
Branch you are in undefined / null 'q.data' is possibly 'undefined'. chapters · patterns from open source Discriminated state in real libraries Query status, Redux actions and state machines: one field decides which other fields exist. A type built this way is called a discriminated union.
1. The problem: a bag of optional flags
Three independent fields allow eight combinations. Only three make sense, and the type cannot tell which.
useOrders.ts
'state.data' is possibly 'undefined'. Why the error? We know "not loading and no error" means data has arrived. The type does not say that. data? is optional on its own, unrelated to the other two fields. So TypeScript still thinks data may be missing. isLoading: true + error set possible in the type no loading, no error, no data also possible checks prove nothing add ! ("trust me, not undefined") or ?. ("stop if undefined") everywhere
2. The fix: one union, one deciding field
A union A | B | C means "exactly one of these shapes". Each shape has a status with a fixed text value, like "pending". A type that allows only one exact value is a literal type. discriminated union Exactly 3 shapes. status is the discriminant (the field that decides). <T> is a type parameter: the data type, filled in later (e.g. Order[]). before the check, q may be any of the 3 shapes q.data: Order[] | undefined only one shape has status "success" drop "pending" and "error" inside the if, q is that one shape (this is narrowing) so data is safe to use q.data: Order[] In the lab, Extract<U, X> means "the members of U that fit X". Pick "pending" or "error": those shapes have data: undefined, so q.data.map is an error.
3. Three libraries, same idea
TanStack Query q.data: Order[] Redux Toolkit Argument of type 'number' is not assignable to parameter of type 'string'. PayloadAction<string> says this action carries a string. createSlice reads that and builds addItem(payload: string). So 42 does not fit (line 11). The action type string is "slice/reducer". Events are a discriminated union on the type field. The FAIL event must carry reason, and line 8 leaves it out. send() only accepts real events with all their fields.
4. Build it: derive the action union from reducers
The Redux Toolkit move in miniature. A mapped type plus a template literal builds every action type. Pieces used: Parameters<F>: the list of F's argument types, as a tuple. infer P: "capture the payload type here and call it P".
ActionOf for the addItem reducer
K is one reducer name its arguments as a tuple matches [any, PayloadAction<infer P>] build the action with a template literal clear has one argument, so the else branch runs CartAction ✓ Type 'number' is not assignable to type 'string'. Type '"cart/additem"' is not assignable to type '"cart/clear" | "cart/addItem"'. Did you mean '"cart/addItem"'? Lower-case i: not one of the two exact action names. Why match exactly [any, PayloadAction<…>]? It requires two arguments. A looser pattern could also match clear (one argument), and give it a useless payload: unknown.
5. A tiny typed state machine
satisfies T checks a value against type T, but keeps the value's own exact types (e.g. "paying", not just State). Here it checks the transition table against your states and events. Record<K, V>: an object with keys K and values V. Partial<T>: T with every key optional. Ev["type"]: the type field of every event, as a union: "PAY" | "SUCCESS" | "FAIL" | "RETRY".
payment-machine.ts
Type '"faild"' is not assignable to type 'State | undefined'. Did you mean '"failed"'? Why? Every target must be a State. "faild" is a typo, not one of the four states. (| undefined appears because Partial made each key optional.) Does data narrow to Order[] here? No: 'data' is possibly 'undefined'
6. No status field? Forbid the other key with never
A plain A | B allows an object that is both. never is the empty type: no value fits it. An optional key of type never can only be left out (or be undefined). So it forbids the other side's key. inclusive or exclusive or Types of property 'error' are incompatible. Type 'Error' is not assignable to type 'undefined'. Member 1 rejects it: error?: never allows only undefined, and an Error does not fit. Member 2 rejects it too: data?: never. No member fits, so it is an error. Tagged union Best default. One literal field (status, type, kind) tells every branch apart. Optional never When you cannot add a tag, e.g. props that are either href or onClick. TanStack Query status: pending | error | success Redux Toolkit type: "slice/reducer" event.type + state value
Remember
Independent flags allow impossible states. One literal field (status, type) picks which other fields exist. TanStack Query narrows data after a status or isSuccess check. Redux Toolkit derives action types as "slice/reducer" with payloads. No tag available? Optional never gives exclusive or. ! Cheat code Model states, not flags. One discriminant field per union. Check it, and the right fields appear. → Go deeper: discriminated unions, exhaustiveness checks, when narrowing is lost, 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.