Zod

4.3.6 · active · verified Sat Apr 18

Zod is a TypeScript-first schema declaration and validation library that provides static type inference, ensuring runtime data matches compile-time types. The current stable version is 4.3.6, with frequent patch and minor releases addressing bug fixes, performance improvements, and new features like `z.fromJSONSchema()`.

Common errors

Warnings

Install

Imports

Quickstart

This example defines a schema for a `User` object, infers its TypeScript type, and demonstrates how to parse valid and invalid data, handling validation errors.

import * as z from "zod";

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

type User = z.infer<typeof UserSchema>;

const validUser: User = UserSchema.parse({
  id: "a1b2c3d4-e5f6-7890-1234-567890abcdef",
  name: "Alice",
  email: "alice@example.com",
});

console.log("Parsed user:", validUser);
// Expected output: Parsed user: { id: '...', name: 'Alice', email: 'alice@example.com' }

try {
  UserSchema.parse({
    id: "invalid-uuid",
    name: "",
    email: "not-an-email",
  });
} catch (error) {
  console.error("Validation error:\n", error);
  // Expected output (abbreviated): Validation error:
ZodError: [
  { code: 'invalid_string', validation: 'uuid', ... },
  { code: 'too_small', minimum: 1, ... },
  { code: 'invalid_string', validation: 'email', ... }
]
}

view raw JSON →