Zod logo

简介

zod logo

Zod

TypeScript 优先的模式验证,使用静态类型推断。

¥

Zod

TypeScript 优先的模式验证,使用静态类型推断。

简介

¥Introduction

Zod 是一个 TypeScript 优先的验证库。使用 Zod,你可以定义用于验证数据的模式,从简单的 string 到复杂的嵌套对象。

¥Zod is a TypeScript-first validation library. Using Zod, you can define schemas you can use to validate data, from a simple string to a complex nested object.

import { z } from "zod/v4";
 
const User = z.object({
  name: z.string(),
});
 
// some untrusted data...
const input = { /* stuff */ };
 
// the parsed result is validated and type safe!
const data = User.parse(input);
 
// so you can use it with confidence :)
console.log(data.name);

特性

¥Features

  • 零外部依赖

    ¥Zero external dependencies

  • 适用于 Node.js 和所有现代浏览器

    ¥Works in Node.js and all modern browsers

  • Tiny:2kb 核心包(gzip 压缩)

    ¥Tiny: 2kb core bundle (gzipped)

  • 不可变 API:方法返回一个新实例

    ¥Immutable API: methods return a new instance

  • 简洁的界面

    ¥Concise interface

  • 适用于 TypeScript 和纯 JS

    ¥Works with TypeScript and plain JS

  • 内置 JSON Schema 转换

    ¥Built-in JSON Schema conversion

  • 广泛的生态系统

    ¥Extensive ecosystem

安装

¥Installation

npm install zod       # npm
deno add npm:zod      # deno
yarn add zod          # yarn
bun add zod           # bun
pnpm add zod          # pnpm

Zod 还会在每次提交时发布一个预览版本。要安装预览版测试:

¥Zod also publishes a canary version on every commit. To install the canary:

npm install zod@canary       # npm
deno add npm:zod@canary      # deno
yarn add zod@canary          # yarn
bun add zod@canary           # bun
pnpm add zod@canary          # pnpm

要求

¥Requirements

Zod 已针对 TypeScript v5.5 及更高版本进行了测试。旧版本可能可以使用,但不受官方支持。

¥Zod is tested against TypeScript v5.5 and later. Older versions may work but are not officially supported.

"strict"

你必须在 tsconfig.json 中启用 strict 模式。这是所有 TypeScript 项目的最佳实践。

¥You must enable strict mode in your tsconfig.json. This is a best practice for all TypeScript projects.

// tsconfig.json
{
  // ...
  "compilerOptions": {
    // ...
    "strict": true
  }
}

"moduleResolution"

你的 "moduleResolution" 应该设置为以下之一。不支持旧版 "node""classic" 模式,因为它们不支持子路径导入。

¥Your "moduleResolution" should be set to one of the following. The legacy "node" and "classic" modes are not supported, as they do not support subpath imports.

  • "node16"(如果 "module" 设置为 "node16"/"node18",则为默认值)

    ¥"node16" (default if "module" is set to "node16"/"node18")

  • "nodenext"(如果 "module" 设置为 "nodenext",则为默认值)

    ¥"nodenext" (default if "module" is set to "nodenext")

  • "bundler"


On this page