zod/valibot schemas + inference
Validate untrusted data with schemas; infer TS types directly from validators; compare zod and valibot; wire into handlers.
Intro
Goal: Treat external input as unknown, validate with a schema, and infer TS types from that schema. You will use zod, see valibot syntax, and make a tiny helper for handlers.
- One source of truth
- safeParse vs parse
- Reuse inferred types
zod infer
Define a schema once. type User = z.infer<typeof userSchema> mirrors validation rules exactly.
import { z } from "zod"
export const userSchema = z.object({
id: z.string().uuid(),
name: z.string().min(1),
age: z.number().int().min(0).optional()
})
export type User = z.infer<typeof userSchema>
// User is kept in sync with runtime rules.All lessons in this course
- zod/valibot schemas + inference
- Defensive parsing and error envelopes