Zod for TypeScript: A Complete Guide with Examples

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Introduction to Zod: What It Is and Why You Need It



In modern web development with TypeScript, one of the key challenges is ensuring data integrity. Even with strict typing, TypeScript cannot guarantee that data coming from external sources (APIs, forms, localStorage, WebSocket) actually matches the declared types. The TypeScript compiler works at development time, but during program execution, types are erased. This is where Zod comes to the rescue.



Zod is a library for declarative data validation and typing for TypeScript and JavaScript. It allows you to create schemas that simultaneously serve as a runtime data validator and a source of truth for static TypeScript types. The core philosophy of Zod is "one schema, two purposes": you write the schema once, and you get both validation and an automatically inferred type.



Key advantages of Zod:

  • Type safety: automatic TypeScript type inference from schemas.
  • Declarative: readable and concise syntax.
  • Composability: schemas can be combined and extended.
  • Detailed errors: clear validation error messages.
  • Zero dependencies: the library requires no additional packages.


Installing Zod



Zod is an npm package, so installation is done via the Node.js package manager. The library is written in TypeScript and comes with ready-made type declaration files, so no additional installation of @types/zod is required.



# Installation via npmnpm install zod

# Installation via yarnyarn add zod

# Installation via pnpmpnpm add zod


After installation, you can import Zod into your project:



import { z } from "zod";


Please note: Zod is not installed via pip, as it is a library for the JavaScript/TypeScript ecosystem, not Python.



Quick Start with a Code Example



Let's create a simple schema for validating user data and immediately see how Zod combines validation and typing.



import { z } from "zod";

// 1. Define the schemaconst UserSchema = z.object({ id: z.number().positive(), name: z.string().min(2, "Name must contain at least 2 characters"), email: z.string().email("Invalid email"), age: z.number().int().min(18, "Age must be at least 18").optional(),});

// 2. Automatically infer the type from the schematype User = z.infer<typeof UserSchema>;

// 3. Validate the dataconst validData = { id: 1, name: "Anna", email: "anna@example.com", age: 25,};

const result = UserSchema.safeParse(validData);

if (result.success) { // result.data has type User console.log("Validation successful:", result.data);} else { // result.error contains detailed error information console.log("Validation errors:", result.error.errors);}

// Example with invalid dataconst invalidData = { id: -1, name: "A", email: "not-an-email",};

const invalidResult = UserSchema.safeParse(invalidData);if (!invalidResult.success) { console.log("Errors:", invalidResult.error.errors); // Will output: // - id: must be a positive number // - name: Name must contain at least 2 characters // - email: Invalid email}


Core Zod Methods and Functions



In this section, we will take a detailed look at 10 key Zod methods that will cover 90% of your validation tasks.



1. z.string() — String Validation

What it does: Creates a schema for validating string values. Provides a chain of methods for applying additional constraints.

Parameters: Does not accept parameters upon creation

Recommendations