Skip to content
Tutorials Center
My learning

Topics

Lesson 74 of 96 ยท TypeScript in Practice

Validating Data with Zod and Type Inference

Use Zod schemas to validate JSON, form input and environment variables at runtime, derive types with z.infer, handle errors and transform data into clean domain values.

TypeScript's types vanish when your program runs. A request body, an environment variable or a config file can contain anything, and the compiler can't help you there. In Typing APIs and JSON Data you saw the idea: describe the shape once as a schema, and derive both the runtime check and the static type from it. This lesson goes deeper with Zod, the most widely used library for that job.

You'll learn the everyday Zod toolbox (objects, unions, refinements, transforms, coercion), how z.infer keeps types and validation in sync, how to read validation errors, and where to apply schemas in a real application. Zod is an npm package, and our in-browser runner has no packages, so the Zod snippets are read-only. The runnable examples use a small hand-written stand-in with the same chainable style, so you can see how this kind of library works inside.

Installing and the first schema

Install Zod like any other dependency (the examples target Zod 4):

Terminal
npm install zod

Then describe the data you expect:

TypeScript
import { z } from 'zod';

const User = z.object({
  id: z.number().int(),
  email: z.string().email(),
  name: z.string().min(1),
  age: z.number().int().min(0).optional(),
});

type User = z.infer<typeof User>;
// { id: number; email: string; name: string; age?: number | undefined }

Two things happen here. User the value is a validator you can call at runtime. User the type is computed from the schema by z.infer, so there's no separate interface to keep in sync. (TypeScript lets a value and a type share a name, because they live in different declaration spaces.)

flowchart LR
  S["Schema<br/>z.object({...})"] -->|"z.infer"| T["Static type<br/>checked by tsc"]
  S -->|".parse() / .safeParse()"| V["Runtime validator<br/>checks real data"]
  D["unknown data<br/>JSON, forms, env"] --> V
  V -->|"valid"| OK["Typed value"]
  V -->|"invalid"| ERR["Error with issues"]

One schema produces both the compile-time type and the runtime check.

parse and safeParse

A schema has two main entry points:

TypeScript
// Throws a ZodError if the data is invalid:
const user = User.parse(JSON.parse(body));

// Never throws; returns a discriminated union:
const result = User.safeParse(JSON.parse(body));
if (result.success) {
  console.log(result.data.email); // typed as string
} else {
  console.log(result.error.issues);
}

Use parse when invalid data is a bug or you have an error handler higher up (an HTTP framework that turns exceptions into 400 responses). Use safeParse when you want to handle failure right there, because the result is a discriminated union that narrows on success. Both give you a new object: by default Zod strips keys that the schema doesn't know about, which is handy for not leaking extra fields into your database.

Failures carry a list of issues, each with a path (where) and a message (what). That's what you show next to form fields or return in an API error body.

Building schemas

Most data is a combination of a few building blocks:

TypeScript
const Role = z.enum(['admin', 'editor', 'viewer']);   // literal union
const Tags = z.array(z.string()).max(5);              // array with a limit
const Point = z.tuple([z.number(), z.number()]);      // fixed-length tuple
const Scores = z.record(z.string(), z.number());      // Record<string, number>
const Id = z.union([z.string().uuid(), z.number()]);  // either form
const Nullable = z.string().nullable();               // string | null
const Defaulted = z.string().default('guest');        // missing -> 'guest'

Each one maps to a type you already know: z.enum to a literal union, z.record to a Record, and .optional() to an optional property. Modifiers such as .min(), .max(), .email() and .regex() don't change the static type (it's still string); they only tighten the runtime check. That's the key limit of types: a type can say "string", but only a schema can say "a string that is a valid email".

For variants that share a tag, use a discriminated union, which is faster and gives better errors than a plain z.union:

TypeScript
const Event = z.discriminatedUnion('type', [
  z.object({ type: z.literal('click'), x: z.number(), y: z.number() }),
  z.object({ type: z.literal('key'), key: z.string() }),
]);

type Event = z.infer<typeof Event>;
// { type: 'click'; x: number; y: number } | { type: 'key'; key: string }

Reuse and compose schemas with .pick(), .omit(), .partial() and .extend(): they mirror the Pick, Omit and Partial utility types, but they also produce a working validator.

Refinements, transforms and coercion

Some rules involve more than one field, or depend on logic. A refinement adds a custom check:

TypeScript
const Signup = z
  .object({
    password: z.string().min(8),
    confirm: z.string(),
  })
  .refine((data) => data.password === data.confirm, {
    message: 'Passwords do not match',
    path: ['confirm'],
  });

A transform converts the parsed value into something else, and z.infer follows the conversion. Zod distinguishes the two sides: z.input<typeof S> is what goes in, and z.output<typeof S> (what z.infer returns) is what comes out:

TypeScript
const CreatedAt = z.string().datetime().transform((text) => new Date(text));

type In = z.input<typeof CreatedAt>;   // string
type Out = z.infer<typeof CreatedAt>;  // Date

Coercion is the special case for data that arrives as text, such as query strings, form fields and environment variables:

TypeScript
const Env = z.object({
  PORT: z.coerce.number().int().default(3000),
  DEBUG: z.stringbool().default(false),
  DATABASE_URL: z.string().url(),
});

export const env = Env.parse(process.env); // fail fast at startup

Validating process.env once at startup is one of the best uses of a schema: a missing or malformed variable stops the app immediately with a clear message, instead of failing later in production.

Try it: a stand-in for the same idea

Here is a small chainable schema library that mimics the style above. It's much smaller than Zod, but it uses the same mechanics: a class that carries the output type T, methods that return new schemas, and an Infer helper.

TypeScript A mini Zod: chainable schemas and Infer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

It prints:

TEXT
{ item: 'Lamp', total: 58.5 }
[
  { path: 'item', message: 'Item must not be empty' },
  { path: 'quantity', message: 'Quantity must be a positive integer' },
  { path: 'unitPrice', message: 'Expected number' }
]

Note how Infer is the "type" half and safeParse the "runtime" half of one value. Because object() collects issues from every field rather than stopping at the first, a form can show all of its problems at once, as Zod does.

Reading errors

A real Zod ZodError exposes the same information as our stand-in: an issues array with path and message. You'll usually reshape it into whatever your UI or API expects:

TypeScript
const result = User.safeParse(input);
if (!result.success) {
  const fieldErrors: Record<string, string> = {};
  for (const issue of result.error.issues) {
    fieldErrors[issue.path.join('.')] = issue.message;
  }
  return { ok: false, fieldErrors };
}

Zod also has helpers for formatting a whole error as text or as a flat tree, and you can pass custom messages to most checks (for example z.string().min(8, 'Use at least 8 characters')).

Where to use schemas

Validate at the boundary, once, where untrusted data enters your program, then pass typed values onward:

  • HTTP handlers: parse the body, query string and route params, return a 400 with the issues if it fails.
  • Forms: reuse one schema on the server and in the browser, so both sides agree on the rules.
  • Environment and config: parse process.env at startup (shown above).
  • External API responses: parse them in the client layer, as in the fetch wrapper from Typing APIs and JSON Data.
  • Stored JSON: data from localStorage or a database JSON column can be stale or hand-edited.

One more trick: with a shared schema, a type and a validator stay together even across a monorepo, so the front end and the back end can import the same definition.

A schema describes what you accept, not everything that could be true. Don't use .parse() as a replacement for authorization or business rules, and remember that z.infer can only be as accurate as the schema you wrote. If the schema says string for a field the server sometimes sends as null, the type will lie just as an unchecked cast would.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does type User = z.infer<typeof UserSchema> give you?

    z.infer computes the TypeScript type from the schema, so the schema is the single source of truth and the type can't drift from the validation.
  2. 2. What is the difference between parse and safeParse?

    safeParse returns a discriminated union (success true with data, or success false with an error), so you can narrow on success instead of catching an exception.
  3. 3. Which check can a schema do that a plain TypeScript type cannot?

    Types only describe categories of values. Constraints such as format, range and length need runtime code, which is what .email(), .positive() and .min() provide.
  4. 4. You parse a form where the age field arrives as the text "42". Which Zod feature fits best?

    Coercion converts text input to the target primitive before validating it, which is exactly what query strings, forms and environment variables need.
  5. 5. Where should you usually run a schema over untrusted data?

    Validate once at the edge and turn the data into a trusted, typed value. Everything after that can rely on the types.

Summary

  • A Zod schema is a runtime validator and the source of a static type: type T = z.infer<typeof Schema>.
  • Use parse to throw and safeParse to get a narrowable success/failure result with path-based issues.
  • Build schemas from objects, arrays, enums, unions, records and discriminated unions; reuse them with pick, omit, partial and extend.
  • refine adds custom rules, transform changes the output type (z.input vs z.output), and z.coerce converts text input.
  • Validate at the boundary: request bodies, forms, process.env, external API responses and stored JSON.
  • A schema is only as truthful as you make it, and it doesn't replace authorization or business rules.

Next: Monorepos and Shared Types