
Zod Has a Free Validation Library — Type-Safe Data Validation in TypeScript
The Validation Problem Your API receives a request body. TypeScript tells you it is type-safe. But TypeScript types disappear at runtime. That user: User could be anything — a string, null, or {hack: true} . You need runtime validation. And it should match your TypeScript types. Zod: Schema Validation That Generates Types Zod is a TypeScript-first schema validation library. Define the schema once, get both runtime validation AND TypeScript types. Basic Usage import { z } from ' zod ' const UserSchema = z . object ({ name : z . string (). min ( 1 ), email : z . string (). email (), age : z . number (). int (). positive (). optional () }) // TypeScript type is GENERATED from the schema type User = z . infer < typeof UserSchema > // { name: string; email: string; age?: number } // Runtime validation const result = UserSchema . safeParse ( requestBody ) if ( ! result . success ) { console . log ( result . error . issues ) // [{ code: 'invalid_string', message: 'Invalid email', path: ['emai
Continue reading on Dev.to Webdev
Opens in a new tab




