Code Reference

Getting Started with Zod

Zod · Reference cheat sheet

Getting Started with Zod

Zod · Reference cheat sheet


📋 Overview

Zod is a TypeScript-first schema library for parsing and validating data at runtime while inferring static types. Common for API payloads, env config, and forms.

🔧 Core concepts

IdeaMeaning
SchemaDeclarative description of a value shape
ParseValidate + return typed data (or throw)
Safe parseValidate without throwing
InferExtract TS type from a schema
TransformMap input → output during parse

Install:

npm install zod
EntryImport
Zod 3import \{ z \} from "zod"
Schemasz.string(), z.object(\{...\}), …

💡 Examples

First schema:

import { z } from "zod";

const User = z.object({
  email: z.string().email(),
  age: z.number().int().positive(),
});

const user = User.parse({ email: "a@b.co", age: 30 });

Type inference:

type User = z.infer<typeof User>;

Env-style parse:

const Env = z.object({ PORT: z.coerce.number().default(9000) });
const env = Env.parse(process.env);

⚠️ Pitfalls

  • parse throws ZodError — use safeParse at trust boundaries if you prefer Result-style control flow.
  • Zod validates runtime values; it does not replace compile-time TS checking alone.
  • Major version APIs differ (Zod 3 vs 4) — match docs to your installed version.

On this page