Schema builders that infer types

How zod-style libraries turn a runtime schema into a static type with z.infer. A free TypeScript lesson with examples.

More on Patterns from open source

Keep learning

Overview

chapters · patterns from open source Schema builders that infer types A validator (or schema) is code that checks data while the program runs. The static type is what TypeScript knows before it runs. To infer is to work a type out automatically.

1. The problem: the type and the validator drift apart

A hand-written type and a hand-written check describe the same data twice. One gets updated, the other does not. Below, the server receives an order as JSON and prints its notes for the kitchen.

order.ts: someone added notes to the type, not to the check

body.notes: string Runtime: TypeError: Cannot read properties of undefined (reading 'toUpperCase') type Order says notes exists never checks notes predicate trusts it compiler happy crash at runtime

2. The idea: one schema, two outputs

two sources of truth Edit one, forget the other. order: Order The runtime check and the type come from the same object. typeof Order means “the type of the value Order”. A value and a type may share a name, because TypeScript keeps them in separate lists. The trick: every schema object carries its output type in a generic (a type with a slot, written Schema<T>). Infer just reads it back. object(), string() and number() above come from this small file.

schema.ts: the whole core in 10 lines

plain meaning a schema whose output has type T S extends Schema<unknown> S must be some kind of schema (a constraint) the type of the _output property of S Record<string, X> an object whose values are all X mapped type: for each key K of S, build a new property

3. Watch Infer walk the schema

typeof Order S is the shape object map each key through Infer read each _output slot What is Courier? Step 1: typeof Courier is the schema returned by object(). Step 2: object() builds its output by visiting each key: name holds a Schema<string>, zones holds a Schema<number[]>. Step 3: Infer reads the _output slot of each child: string and number[]. Step 4: the outer Infer unwraps the outer Schema, so you get the plain object type, not a Schema.

4. Chained methods change the output type

Each method returns a new schema with a new T. That is how .optional() and .transform() reshape the inferred type. string | undefined Returns a new schema whose output is T | undefined (“T or nothing”). Here T is string. Validation and a brand (an invisible tag, so plain strings no longer fit UserId) in one step.

the optional-key gap

The fix below uses two tools. A extends B ? X : Y is a conditional type: “if A fits B, then X, else Y”. Exclude<U, V> removes V's members from the union U.

OptionalKeys , step by step

for each key, ask: does undefined fit its type? keep the key name or never (the empty type) [keyof T] reads all values as a union never | "notes" never vanishes from a union FixOptional: required keys & ?: keys Real libraries do this split inside object(), then flatten the intersection so hovers stay readable.

5. How the libraries do it

Same idea with small standalone functions instead of methods, so bundlers can drop unused validators. Older API, same move: the schema object carries a type parameter that a helper type reads. string DSL A string DSL (a mini language inside a string). Template literal types read definitions like "string | number[]" and turn them into a static type. Schema first (zod, Valibot) Runtime schema is the source. Type is derived. Great where outside data enters (untrusted boundaries): API bodies, forms, env vars. Type first (interfaces + codegen)

Remember

Writing the type and the validator separately lets them drift. A schema object carries its output type in a generic (a phantom slot). Infer<S> is just an indexed access into that slot. object() is a mapped type that runs Infer over every key. Each chained method returns a schema with a new output type. ! Cheat code Schema<T> carries T. Infer reads T. object() maps Infer over the shape. Validate at the edge, infer everywhere else. → Go deeper: mapped types, indexed access types, generic classes and builder chains, JSON.parse leaked any, branded 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.