DEV Community

Alex Spinov
Alex Spinov

Posted on

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
}
Enter fullscreen mode Exit fullscreen mode

API Request Validation

// Express middleware
app.post("/api/users", (req, res) => {
  const result = UserSchema.safeParse(req.body)
  if (!result.success) {
    return res.status(400).json({ errors: result.error.flatten() })
  }
  // result.data is fully typed
  createUser(result.data)
})
Enter fullscreen mode Exit fullscreen mode

Schema Composition

// Extend schemas
const AdminSchema = UserSchema.extend({
  permissions: z.array(z.string()),
})

// Partial (all fields optional)
const UpdateUserSchema = UserSchema.partial()

// Pick/Omit
const LoginSchema = UserSchema.pick({ email: true }).extend({
  password: z.string().min(8),
})

// Transform
const StringToNumber = z.string().transform(Number)

// Discriminated unions
const EventSchema = z.discriminatedUnion("type", [
  z.object({ type: z.literal("click"), x: z.number(), y: z.number() }),
  z.object({ type: z.literal("scroll"), offset: z.number() }),
])
Enter fullscreen mode Exit fullscreen mode

Why Zod

  • Single source of truth — schema = types = validation
  • 25M+ weekly npm downloads — the ecosystem standard
  • Works everywhere — Node, Deno, Bun, browsers, React Native
  • Composable — extend, merge, transform, pipe schemas
  • Error messages — customizable, i18n-ready
  • Framework integrations — tRPC, React Hook Form, Astro, Next.js
npm install zod
Enter fullscreen mode Exit fullscreen mode

Building type-safe applications? Check out my developer tools or email spinov001@gmail.com.

Top comments (0)