TypeScript Conditional Types and infer Explained
If-else at the type level with T extends U ? X : Y, and infer to pull a piece out of a type, such as a return or element type.
In this chapter
Conditional types and infer
More on keyof, indexed, mapped and conditional types
Keep learning
Overview
chapters · keyof, indexed, mapped and conditional types Conditional types and infer If-else at the type level, and infer to pull a piece out of a type. Words first. A generic type like Unwrap<T> has a blank T, filled when you use it. A conditional type picks one of two types based on a test. never is the empty type: no value fits it.
1. The problem: copying a type that already exists
An API helper returns a Promise of a payment. (A Promise is a box for a value that arrives later.) Callers want the payment type itself, so someone retypes it. retyped by hand The copy drops currency. Nobody notices until the UI needs it. "EUR" | "USD" Unwrap takes the Promise box off. Change the API and Payment follows. Section 3 explains how.
2. A ternary for types
A extends B ? X : Y asks: "is A assignable to B?", which means "does every A value fit into B?" Yes gives X, no gives Y. Here extends is a test, not inheritance. input type extends string ? assignability test if yes 'hi' is a literal type (one exact value). Every literal string fits into string "text" | "other" any (the "switch off checking" type) might or might not be a string, so TypeScript returns both branches as a union (either-or)
3. infer: a blank to fill in
infer U declares a new type variable (a named blank) inside the pattern. TypeScript lines the real type up with the pattern. If the shapes match, U holds the piece that sat where U was.
Unwrap >
plug in T Promise<Payment> extends Promise<infer U> ? U : Promise<Payment> match the shapes: U lines up with Payment match succeeded: take the true branch
Unwrap (no match)
plug in T number extends Promise<infer U> ? U : number a number is not a Promise (it has no then method): match fails false branch
infer only exists in the extends clause
Without the word infer, TypeScript thinks U is a type defined somewhere else. None exists, so it can't find the name.
4. infer anywhere in the pattern
Put infer where the piece you want sits. This is how the built-in helpers work. Syntax in the table: ...args means "all the remaining parameters". A tuple is a fixed-length array with a type per position, like [string, number]. readonly means it can't be changed. pulls out parameter tuple (Parameters) first parameter T extends readonly (infer E)[] ? E : never array element T extends [infer H, ...infer Tail] ? H : never first tuple item a property, if it exists Apply to an event handler Grab the payload type from a callback signature you do not own. an API response Peel the envelope off a paginated response. The input has no data property, so the shapes do not match. The false branch is never, the empty type.
5. infer with a constraint: infer U extends string
Add extends after infer U. The match fails unless U fits. With number it can even turn the text "42" into the number type 42. The backticks in ToNum form a template literal type: a pattern for strings. means "a string that is just a number, written out". string "42" becomes number 42 "abc" is not a written number, so no match: false branch, never FirstStr<['cart', 2]> FirstStr<[2, 'cart']> first item is not a string
6. Recursion: keep unwrapping
Unwrap: one layer Awaited: all layers How it works: if T is a Promise, take what's inside and run DeepUnwrap again on it. Stop when it is no longer a Promise. In real code, use the built-in Awaited. It also handles thenables: objects with a then method that act like Promises.
Remember
A extends B ? X : Y is a ternary on assignability. infer N extends number filters and converts "42" to 42. Recurse in the true branch to peel every layer. ! Cheat code
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.