CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-zod

TypeScript-first schema validation library with static type inference. Define schemas, validate data, and get type safety with zero dependencies.

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

index.mddocs/

Zod

TypeScript-first schema validation library with static type inference. Define schemas, validate data, and get type safety with zero dependencies.

Quick Start

import * as z from 'zod';

// Define a schema
const User = z.object({
  name: z.string(),
  age: z.number().int().positive(),
  email: z.string().email(),
});

// Parse and validate
const user = User.parse({ name: 'Alice', age: 30, email: 'alice@example.com' });

// Safe parsing (no throw)
const result = User.safeParse({ name: 'Bob', age: 25 });
if (result.success) {
  console.log(result.data);
} else {
  console.error(result.error.issues);
}

// Type inference
type User = z.infer<typeof User>;

Core Concepts

  • Schemas: Immutable validation rules created with factory functions (z.string(), z.object(), etc.)
  • Parsing: Validate data with parse() (throws) or safeParse() (returns result)
  • Type Inference: Extract TypeScript types from schemas using z.infer<T>
  • Method Chaining: Chain validators and modifiers: z.string().min(3).email()
  • Transformations: Transform validated data with transform() and refine()

Quick Reference

Primitive Schemas

z.string()      // String validator
z.number()      // Number validator
z.boolean()     // Boolean validator
z.date()        // Date validator
z.bigint()      // BigInt validator
z.null()        // Null validator
z.undefined()   // Undefined validator
z.any()         // Accepts any value
z.unknown()     // Unknown type
z.never()       // Always fails

Complex Schemas

z.object({ ... })           // Object schema
z.array(schema)              // Array schema
z.tuple([...])              // Tuple schema
z.record(key, value)        // Record/dictionary
z.map(key, value)           // Map schema
z.set(value)                // Set schema
z.enum([...])               // Enum schema
z.union([...])              // Union schema
z.intersection(a, b)        // Intersection schema

Common Modifiers

.optional()      // Make optional
.nullable()      // Accept null
.nullish()       // Accept null or undefined
.default(value)  // Provide default
.catch(value)    // Catch errors
.readonly()      // Make readonly
.brand<T>()      // Add type brand

Parsing Methods

schema.parse(data)              // Parse (throws on error)
schema.safeParse(data)          // Safe parse (returns result)
schema.parseAsync(data)         // Async parse
schema.safeParseAsync(data)     // Async safe parse

Type Utilities

z.infer<typeof schema>          // Extract output type
z.output<typeof schema>         // Extract output type (alias)
z.input<typeof schema>          // Extract input type

Common Patterns

Form Validation

const FormSchema = z.object({
  email: z.string().email(),
  password: z.string().min(8),
  age: z.number().int().min(18),
});

const result = FormSchema.safeParse(formData);

API Request Validation

const ApiRequest = z.object({
  userId: z.string().uuid(),
  action: z.enum(['create', 'update', 'delete']),
  data: z.record(z.string(), z.any()),
});

Environment Variables

const EnvSchema = z.object({
  PORT: z.coerce.number().int().min(1).max(65535),
  DATABASE_URL: z.string().url(),
  DEBUG: z.coerce.boolean().default(false),
});

const env = EnvSchema.parse(process.env);

Error Handling

try {
  const data = schema.parse(input);
} catch (error) {
  if (error instanceof z.ZodError) {
    // Handle validation errors
    console.error(error.issues);
    console.error(error.format());
    console.error(error.flatten());
  }
}

Documentation Structure

Guides

  • Quick Start Guide - Step-by-step getting started tutorial

Examples

Reference

Installation

npm install zod

Package Information

  • Package: zod
  • Type: npm
  • Language: TypeScript
  • Version: 4.3.5

docs

index.md

tile.json