Back to articles
Zod Has a Free Validation Library: TypeScript-First Schema Validation With Zero Dependencies

Zod Has a Free Validation Library: TypeScript-First Schema Validation With Zero Dependencies

via Dev.to JavaScriptAlex Spinov

You validate form input with if statements. You parse API responses with type assertions. You trust that JSON.parse returns what you expect. Then production crashes because someone sent "123" instead of 123 . What if your validation automatically generated TypeScript types — and caught every malformed input at runtime? That's Zod. Define a schema once, get both runtime validation AND TypeScript types. The Core Concept import { z } from " zod " ; // Define schema const UserSchema = z . object ({ name : z . string (). min ( 1 ). max ( 100 ), email : z . string (). email (), age : z . number (). int (). positive (). max ( 150 ), role : z . enum ([ " admin " , " user " , " moderator " ]), tags : z . array ( z . string ()). max ( 10 ). default ([]), }); // Extract TypeScript type — automatically! type User = z . infer < typeof UserSchema > ; // { name: string; email: string; age: number; role: "admin" | "user" | "moderator"; tags: string[] } // Validate at runtime const result = UserSchema

Continue reading on Dev.to JavaScript

Opens in a new tab

Read Full Article
2 views

Related Articles