Schema Composition and Reuse
Build larger schemas from smaller ones using .extend(). This avoids duplication and keeps your schemas maintainable. Try removing createdAt from the input. The base schema requires it.
import { z } from 'zod';
// Base schema with shared fields
const BaseEntitySchema = z.object({
id: z.number(),
createdAt: z.string(),
});
// Extend to add domain-specific fields
const UserSchema = BaseEntitySchema.extend({
name: z.string(),
email: z.email(),
});
// .extend() overrides a field if you redeclare it
// Note: .merge() was deprecated in Zod v4 — use .extend() insteadtype BaseEntity = {
id: number;
createdAt: string;
};
type User = {
id: number;
createdAt: string;
name: string;
email: string;
}{
"id": 1,
"createdAt": "2024-01-15",
"name": "Alice",
"email": "alice@example.com"
}