Generic classes and builder chains
Each method call returns a new, more precise type: the trick behind query builders and schema libraries. A free TypeScript lesson with examples.
More on Generics
Keep learning
Overview
chapters · generics Generic classes and builder chains Each method call returns a new, more precise type. That is the trick behind query builders and schema libraries.
1. A form builder that knows nothing
Reminder: a generic has a type blank like T, filled in when you use it. Here we use that inside classes. A signup form is built field by field. The result is a bag of unknown (the "could be anything" type). Typos pass. unknown (no error!) 'values.email' is of type 'unknown'. Line 9: the type says "any key name is fine", so the typo emial is allowed. The builder saw every field name and parser at runtime. It just never wrote them into its type.
2. Generic classes: T for the whole instance
A class type parameter (the <T> after the class name) is shared by every method. Fill it once, at new. Argument of type 'string' is not assignable to parameter of type 'number'. Line 7 fills T with number. So set now expects a number, and the string '4.50' doesn't fit. new PriceCache<number>() new Box(5) new PriceCache() no type given and no argument to read it from, so T falls back to unknown
3. Builders: return a new type from each call
New syntax in the code below, in plain words: A & B: an intersection, "has everything from A and everything from B". out as Shape: a cast, "trust me, this has type Shape".
Watch Shape grow
new Form() age: number Now the typo is caught. The type of v lists exactly email, age and vip, and emial is not among them. (formData is the raw form input, a string per field.) Note the one cast in build (out as Shape). Inside the loop, TypeScript only sees a loose object, so it cannot prove the result has type Shape. The chain of field calls guarantees it, so the cast is safe.
4. Why return a new instance, not this
A new Form object gets a new type. Each step is immutable (never changes the old builder), so a half-built form can be reused safely.
5. When the type does not change: return this
returns the base class Property 'page' does not exist on type 'Query'. where promises a plain Query. So after .where(…), TypeScript forgets it was a PagedQuery, and page is gone. returns this Called on a PagedQuery, this means PagedQuery. So page is still there.
6. A select that narrows the rows
A second type parameter tracks the chosen columns. Fix Row once, infer the keys per call. keyof Row: the union (either-or list) of Row's key names, e.g. 'id' | 'total' | 'status'. Pick<Row, K>: a built-in type that keeps only the keys K from Row. Pick<Order, "id" | "total">[] Property 'status' does not exist on type 'Pick<Order, "id" | "total">'. You selected only id and total, so each row's type has only those two keys. Asking for status is an error. Order has id, total and status. What happens? Select<Order, "tip"> Select<Order, never> Error on 'tip' Select<Order, keyof Order> Step 1: select says K extends keyof Order: K must be one of 'id' | 'total' | 'status'. Step 2: TypeScript reads K from the argument: 'tip'. Step 3: 'tip' is not one of those names, so the call fails: Argument of type '"tip"' is not assignable to parameter of type 'keyof Order'. new Select<Order>() Row fixed by hand K inferred Select<Order, "id" | "total"> new type Pick<Order, …>[] The class splits type arguments: one explicit, the rest inferred.
Remember
A class type parameter is shared by all its methods. Fix one type at new, infer the rest in methods. ! Cheat code Each step returns Builder<Shape & Added>. Same type? Return this. One cast at the end. returns this Same type each call. Good for fluent setters and subclass chains. returns Builder<New> Type grows each call. Good for forms, queries, schemas. Zod-style schemas object shape grows per key Query builders selected columns narrow rows routes accumulate into a map → Deeper: schema builders that infer types, classes in TypeScript, partial inference and currying, mapped types.
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.