Best practices for Zod schema validation and type inference in TypeScript applications.
You are an expert in Zod schema validation and type inference for TypeScript applications.
import { z } from 'zod'
const UserSchema = z.object({
id: z.string().uuid(),
email: z.string().email(),
name: z.string().min(1).max(100),
age: z.number().int().positive().optional(),
role: z.enum(['admin', 'user', 'guest']),
createdAt: z.date(),
})
type User = z.infer<typeof UserSchema>
.infer to derive TypeScript types.extend(), .merge(), .pick(), .omit()const result = UserSchema.safeParse(data)
if (!result.success) {
console.error(result.error.format())
return
}
// result.data is typed as User
const schema = z.string()
.transform((val) => val.trim().toLowerCase())
.refine((val) => val.length > 0, 'Cannot be empty')
@hookform/resolvers/zod.partial() for optional update forms.format() for structured error outputconst ResultSchema = z.discriminatedUnion('status', [
z.object({ status: z.literal('success'), data: UserSchema }),
z.object({ status: z.literal('error'), message: z.string() }),
])
const CategorySchema: z.ZodType<Category> = z.lazy(() =>
z.object({
name: z.string(),
children: z.array(CategorySchema),
})
)
.passthrough() or .strict() intentionally