Zod: Schema as Single Source of Truth
What you'll learn: How Zod schemas both validate runtime data and automatically generate TypeScript types, eliminating duplication between your type definitions and validation logic.
You've seen the problem: when you fetch data from an API, you write a TypeScript interface to describe it, then separately write validation code to check if the runtime data actually matches. You maintain two sources of truth that can drift apart.
Zod solves this by making the schema the single source of truth. You define your data structure once as a Zod schema, which validates at runtime and automatically generates the corresponding TypeScript type.
The Traditional Problem
Previously, you'd write:
// The TypeScript type
interface User {
id: number;
name: string;
email: string;
}
// Separate validation logic
function validateUser(data: unknown): data is User {
// Manual checks here...
}
Two definitions that must stay synchronized manually.
Zod's Approach: Schema First
With Zod, you define the structure once:
import { z } from 'zod';
// Define the schema
const UserSchema = z.object({
id: z.number(),
name: z.string(),
email: z.string()
});
// Extract the TypeScript type automatically
type User = z.infer<typeof UserSchema>;
Now User is derived from UserSchema. The schema validates at runtime, and TypeScript knows the exact shape. If you change the schema, the type updates automatically — no manual synchronization needed.
Why This Matters
When the schema is the single source of truth, you eliminate an entire class of bugs where your types claim something is safe, but your validation logic doesn't actually enforce it. Change the schema once, and both runtime safety and compile-time types update together.
Key Takeaway: Zod schemas serve dual duty — they validate data at runtime and generate TypeScript types via z.infer, making your schema the authoritative definition of your data shape.