Zod – TypeScript-first schema declaration and validation library
Zod is a TypeScript-first schema validation library designed to be type-safe and declarative. It allows you to define data schemas, validate inputs, and automatically generate TypeScript types. Zod is especially useful for validating data from APIs, forms, or configurations.
📦 Installation
Section titled “📦 Installation”Install Zod via npm or yarn:
npm install zod# oryarn add zod🔧 Basic Usage
Section titled “🔧 Basic Usage”1. Define a Schema
Section titled “1. Define a Schema”import { z } from "zod";// Define a schema for a "User" objectconst UserSchema = z.object({ id: z.string().uuid(), name: z.string().min(2), age: z.number().int().positive(), email: z.string().email(),});2. Validate Data
Section titled “2. Validate Data”const userData = { id: "550e8400-e29b-41d4-a716-446655440000", name: "Alice", age: 30, email: "alice@example.com",};const result = UserSchema.safeParse(userData);if (result.success) { console.log("Validation successful:", result.data);} else { console.error("Validation error:", result.error);}✨ Advanced Features
Section titled “✨ Advanced Features”Nested Schemas
Section titled “Nested Schemas”const AddressSchema = z.object({ street: z.string(), city: z.string(), zipCode: z.string().regex(/^\d{5}$/),});const UserWithAddressSchema = UserSchema.extend({ address: AddressSchema,});Arrays and Complex Types
Section titled “Arrays and Complex Types”const UserArraySchema = z.array(UserSchema);const OptionalUserSchema = UserSchema.optional();const NullableUserSchema = UserSchema.nullable();Transformations
Section titled “Transformations”const UserWithFullNameSchema = UserSchema.extend({ fullName: z.string(),}).transform((user) => ({ ...user, fullName: `${user.name} (${user.email})`,}));🔍 API Validation
Section titled “🔍 API Validation”Zod is ideal for validating API responses:
const ApiResponseSchema = z.object({ status: z.literal("success"), data: z.array(UserSchema),});const apiResponse = { status: "success", data: [ { id: "550e8400-e29b-41d4-a716-446655440000", name: "Alice", age: 30, email: "alice@example.com", }, ],};const parsedResponse = ApiResponseSchema.parse(apiResponse);📚 Best Practices
Section titled “📚 Best Practices”- Reuse your schemas: Define base schemas and extend them.
- Use
safeParse: To handle validation errors gracefully. - Document your schemas: Add descriptions to clarify their usage.
📖 Official Documentation
Section titled “📖 Official Documentation”For more details, check out the official Zod documentation.
💡 Complete Example
Section titled “💡 Complete Example”Here’s a complete example of using Zod in a TypeScript project:
import { z } from "zod";// 1. Define a schemaconst ProductSchema = z.object({ id: z.string().uuid(), name: z.string().min(1), price: z.number().positive(), inStock: z.boolean(),});// 2. Validate user inputconst userInput = { id: "550e8400-e29b-41d4-a716-446655440000", name: "Laptop", price: 999.99, inStock: true,};const product = ProductSchema.parse(userInput);console.log(product); // { id: "...", name: "Laptop", price: 999.99, inStock: true }