Installing and Basic Zod Usage
What you'll learn: How to install the Zod validation library and use it to define a simple schema that validates data and throws errors when validation fails.
Why Zod?
Remember how TypeScript's types disappear at runtime? When external data arrives from an API, TypeScript can't protect you—it only knows what you claim the data looks like. Zod bridges this gap by letting you define schemas that validate data at runtime and automatically infer TypeScript types from those schemas.
Installing Zod
Install Zod via npm in your TypeScript project:
npm install zod
That's it—Zod has no peer dependencies and works immediately.
Your First Schema
Import Zod and define a schema using z.object():
import { z } from 'zod';
const UserSchema = z.object({
id: z.number(),
name: z.string(),
email: z.string()
});
This schema describes an object with three required properties: id (number), name (string), and email (string).
Validating with .parse()
Use .parse() to validate data. If validation succeeds, you get back the typed data. If it fails, Zod throws an error:
const validData = { id: 1, name: "Alice", email: "alice@example.com" };
const user = UserSchema.parse(validData);
// user is now typed: { id: number; name: string; email: string; }
const invalidData = { id: "not-a-number", name: "Bob" };
UserSchema.parse(invalidData); // Throws ZodError!
Key Takeaway: Install Zod with npm install zod, define schemas with z.object(), and use .parse() to validate data and throw on errors—giving you runtime safety that matches your TypeScript types.