TypeScript Generic Constraints and Defaults (extends)
Limit a type parameter with T extends …, combine it with keyof, and give it a default. Examples and the errors constraints prevent.
In this chapter
Constraints and defaults
More on Generics
Keep learning
Overview
chapters · generics Constraints and defaults extends limits what a type parameter accepts. A default fills it when nobody passes one. Reminder: a type parameter like T is a blank for a type, filled in on each call. A constraint is a rule about what may go in that blank.
two helpers for a food delivery app
Property 'length' does not exist on type 'T'. Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'unknown'. Line 2: a number has no .length. Since T might be a number, TypeScript refuses. Line 6: "implicitly has an 'any' type" means TypeScript couldn't work out a type and gave up. You can't look up a key by name on unknown, because it might not be an object at all. The fix is not any (which switches checking off). It is telling TypeScript what every T must have.
2. extends means “must fit into”
T can be any type, as long as it has a numeric length. fits into a.length: number longest('wok', 'grill') "wok" | "grill" longest(['a'], ['b', 'c']) arrays too any shape with length longest(1, 2) Think of the constraint as the type of the slot. The caller can pass anything that fits it.
3. One parameter constrains another
keyof T is the union (either-or list) of T's key names. For Order it is 'id' | 'total' | 'status'. So K extends keyof T means: K must be one of those names. Then T[K] means "the type stored under key K in T". get(order, 'total') get(order, 'status') "pending" | "paid" get(order, 'tip') Argument of type '"tip"' is not assignable to parameter of type 'keyof Order'. Order has no key named tip. Bonus: the editor now autocompletes 'id' | 'total' | 'status' for the second argument.
4. Constraint vs plain annotation
Both accept the same arguments. Only the generic remembers the extra fields. Below, order is a value of the Order type from section 3. annotation: forgets constraint: remembers
How TypeScript reaches this error
promise in the signature returns T what T might be for some caller what the body returns no: total and status missing error: not assignable to 'T'
5. Defaults: the value when nobody passes one
you write TData, TError unknown, Error both defaults Order, Error first given, second default ApiResult<Order, string> Order, string Default rules constraint + default What is the type of b? bare T T extends X limits what callers pass lets you use members inside used when nothing is inferred
Remember
A bare T has no members you can use. T extends X: callers must pass something assignable to X. K extends keyof T plus T[K] types key lookups. Defaults go last and must satisfy their constraint. ! Cheat code when the body needs a member of T when most callers want one common type → Deeper: generics as functions, typeof and keyof, indexed access types, how inference works.
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.