Schema validation with zod & inference to TS
Validate requests with zod; infer TypeScript types from schemas; add safe middleware and error handling.
Intro
Goal: Validate inbound data with zod and keep TypeScript types in sync via z.infer. You will parse safely, send helpful errors, and plug validation into middleware.
- Define schemas once
- Infer TS types
- safeParse + 400 errors
Schema + infer
Model once with zod. The derived type User = z.infer<typeof userSchema> mirrors validation exactly.
import { z } from "zod"
export const userSchema = z.object({
id: z.string().regex(/^u_[a-z0-9]+$/),
name: z.string().min(1),
age: z.number().int().nonnegative().optional()
})
export type User = z.infer<typeof userSchema>
// Reuse `User` across handlers, services, and testsAll lessons in this course
- Router handlers, Request/Response typing
- Schema validation with zod & inference to TS
- Error middleware & result types