Back to Snippets
TypeScriptTypeScript

TypeScript Zod Validation

Runtime schema validation with automatic TypeScript type inference.

typescriptzodvalidationschema
import { z } from class=class="text-emerald-400">"text-emerald-400">'zod'

const UserSchema = z.object({
  id: z.number(),
  name: z.string().min(2).max(50),
  email: z.string().email(),
  age: z.number().int().min(0).max(150).optional(),
  role: z.enum([class=class="text-emerald-400">"text-emerald-400">'admin', class=class="text-emerald-400">"text-emerald-400">'editor', class=class="text-emerald-400">"text-emerald-400">'viewer']),
  metadata: z.record(z.string()).optional(),
})

class=class="text-emerald-400">"text-gray">// Infer the TypeScript type from the schema
type User = z.infer<typeof UserSchema>

class=class="text-emerald-400">"text-gray">// Validate unknown data
function parseUser(data: unknown): User {
  return UserSchema.parse(data)
}

class=class="text-emerald-400">"text-gray">// Safe parse — returns result instead of throwing
function safeParseUser(data: unknown) {
  const result = UserSchema.safeParse(data)
  if (!result.success) {
    console.error(result.error.flatten())
    return null
  }
  return result.data
}

How to Use

Define schemas once and get both validation and types: type User = z.infer<typeof UserSchema>. Use parse() when you want to throw on invalid data, or safeParse() for graceful error handling in APIs and forms.

Related Technology

TypeScript

Have a Project in Mind?

Let's discuss how we can bring your idea to life. From initial concept to production-ready product — we've got you covered.

or book a free call