
Zod Has a Free API: Runtime Type Validation That TypeScript Should Have Built In
TypeScript types disappear at runtime. Zod brings them back. What Is Zod? Zod is a TypeScript-first schema validation library. Define a schema once, get both runtime validation AND TypeScript types — no duplication. import { z } from " zod " const UserSchema = z . object ({ name : z . string (). min ( 2 ), email : z . string (). email (), age : z . number (). int (). min ( 18 ). max ( 120 ), role : z . enum ([ " admin " , " user " , " moderator " ]), }) // Extract TypeScript type from schema type User = z . infer < typeof UserSchema > // { name: string; email: string; age: number; role: "admin" | "user" | "moderator" } // Runtime validation const result = UserSchema . safeParse ( requestBody ) if ( ! result . success ) { console . log ( result . error . issues ) // Detailed error messages } else { console . log ( result . data ) // Fully typed User object } API Request Validation // Express middleware app . post ( " /api/users " , ( req , res ) => { const result = UserSchema . safePars
Continue reading on Dev.to Webdev
Opens in a new tab



