Zod — A Powerful Data Validation Library for TypeScript

онлайн тренажер по питону

What is Zod?

Zod is a library for declarative data validation and parsing, written in TypeScript. It allows you to describe data schemas (schemas are strict type descriptions) and check any objects, strings, numbers, etc. for compliance. The main feature of Zod is full integration with TypeScript: types are automatically inferred based on the schema, eliminating duplicate definitions.

Why is data validation needed?

In real applications, data often comes from external sources (APIs, forms, configuration files, localStorage). Without validation, it's easy to get bugs, XSS attacks, or unexpected behavior. Zod guarantees that the data matches the expected structure and throws clear errors if something is wrong.

Installation

npm install zod

The library requires no additional configuration and works both in Node.js and in the browser (with a bundler).

Main Features

  • Schema creation: z.string(), z.number(), z.object(), z.array(), etc.
  • Parsing and validation: the .parse() method returns data or throws an error; .safeParse() returns an object with success/data/error fields.
  • Transformation: .transform() allows you to modify data after successful validation.
  • Refine: custom checks using .refine().
  • Type inference: z.infer<typeof schema> generates a TypeScript type.

TypeScript Code Example

import { z } from 'zod';

// Define a schema for a userconst UserSchema = z.object({ id: z.number().int().positive(), name: z.string().min(2).max(50), email: z.string().email(), age: z.number().min(18).max(120).optional(), role: z.enum(['admin', 'user', 'guest'])});

// Infer a type based on the schematype User = z.infer<typeof UserSchema>;

// Use safeParse for safe validationconst rawData = { id: 1, name: 'Anna', email: 'anna@example.com', age: 25, role: 'admin'};

const result = UserSchema.safeParse(rawData);if (result.success) { console.log('Data is valid:', result.data);} else { console.error('Errors:', result.error.errors);}

When to use Zod

Zod is ideal for:

  • Validating API input data (e.g., in Express or Next.js).
  • Checking form data on the client and server.
  • Parsing environment variables (dotenv + Zod).
  • Working with configuration files (JSON/YAML).
  • Creating strict types for dynamic data.

Thanks to full TypeScript support, Zod makes code safer and more readable, eliminating desynchronization between types and actual data.