Introduction

Zod is a TypeScript-first schema validation library. It allows you to define schemas that provide both runtime validation and compile-time type inference.

What is Zod?

Zod lets you define schemas that:

  • Validate data at runtime
  • Infer TypeScript types
  • Provide detailed error messages
  • Compose complex schemas

Basic Example

import { z } from "zod";

// Define schema
const UserSchema = z.object({
  id: z.number(),
  name: z.string().min(1),
  email: z.string().email(),
  age: z.number().optional(),
});

// Infer TypeScript type
type User = z.infer<typeof UserSchema>;

// Validate data
const user = UserSchema.parse({
  id: 1,
  name: "Alice",
  email: "alice@example.com",
});

Schema Types

Primitives

z.string();
z.number();
z.boolean();
z.date();
z.null();
z.undefined();

Objects

const schema = z.object({
  name: z.string(),
  age: z.number(),
});

Arrays

z.array(z.string());
z.string().array(); // Alternative syntax

Unions

z.union([z.string(), z.number()]);
z.string().or(z.number()); // Alternative

Validation

Parse (Throws on Error)

try {
  const user = UserSchema.parse(invalidData);
} catch (error) {
  console.error(error.errors);
}

Safe Parse (Returns Result)

const result = UserSchema.safeParse(data);

if (result.success) {
  console.log(result.data);
} else {
  console.error(result.error);
}

Tools

Use our tools:

Conclusion

Zod provides:

Benefits:

  • Runtime validation
  • Type inference
  • Great error messages
  • Composable schemas

Use for:

  • API validation
  • Form validation
  • Configuration validation
  • Type-safe parsing

Next Steps