All Resources
Library
TypeScriptValidationSchema
May 29, 2024

Zod Schema Validation

TypeScript-first schema validation with static type inference.

Overview

Zod is a TypeScript-first schema validation library with static type inference. Define a schema once and get both validation and TypeScript types automatically.

Key Features

  • Type Inference: Automatic TypeScript types from schema
  • Composable: Build complex schemas from simple primitives
  • Custom Validation: Easy custom error messages
  • Async Validation: Support for async validators
  • Transformations: Parse and transform data

Quick Start

npm install zod

Basic Validation

import { z } from 'zod'

const UserSchema = z.object({
  id: z.number(),
  name: z.string().min(1),
  email: z.string().email(),
  age: z.number().int().positive().optional()
})

// Inferred type: { id: number; name: string; email: string; age?: number }
type User = z.infer<typeof UserSchema>

const result = UserSchema.parse({
  id: 1,
  name: 'Alice',
  email: 'alice@example.com'
})

Error Handling

const result = UserSchema.safeParse({
  id: 'not a number',
  name: '',
  email: 'invalid-email'
})

if (!result.success) {
  console.log(result.error.errors)
  // [
  //   { path: ['id'], message: 'Expected number, received string' },
  //   { path: ['name'], message: 'String must contain at least 1 character' },
  //   { path: ['email'], message: 'Invalid email' }
  // ]
}

Async Validation

const userSchema = z.object({
  email: z.string().email().refine(
    async (email) => {
      const exists = await checkEmailInDatabase(email)
      return !exists
    },
    { message: 'Email already exists' }
  )
})

Zod eliminates runtime type errors with compile-time safety.

Curated by

Shyam