Inferring Types from Zod Schemas
What you'll learn: How to automatically derive TypeScript types from your Zod validation schemas, eliminating redundant type definitions.
The Core Idea
One of Zod's most powerful features is its ability to work backward: once you've defined a schema that validates your runtime data, you can extract the corresponding TypeScript type directly from it using z.infer<typeof schema>. This means you write your validation logic once, and TypeScript types flow automatically from that single source of truth.
Think of it like a mold and its casting—your Zod schema is the mold, and z.infer creates the TypeScript type (the casting) that perfectly matches that shape.
How It Works
When you create a Zod schema, TypeScript understands its structure at compile time. The z.infer utility type analyzes the schema definition and produces the equivalent TypeScript type:
import { z } from 'zod';
const UserSchema = z.object({
id: z.number(),
name: z.string(),
email: z.string(),
age: z.number().optional()
});
// Extract the type from the schema
type User = z.infer<typeof UserSchema>;
// Equivalent to:
// type User = {
// id: number;
// name: string;
// email: string;
// age?: number;
// }
Notice you don't write the User type manually—Zod generates it for you. If you change the schema, the type updates automatically.
Using Inferred Types
Once extracted, these types work like any other TypeScript type:
function processUser(user: User) {
console.log(user.name);
// user.age is number | undefined
}
Key Takeaway: Use z.infer<typeof schema> to automatically generate TypeScript types from Zod schemas, keeping your validation logic and type definitions perfectly synchronized.