Zod logo

简介

zod logo

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 * as z from "zod";
 
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

  • 零外部依赖
  • 适用于 Node.js 和所有现代浏览器
  • 微小:2kb 核心包(gzip 压缩)
  • 不可变 API:方法返回一个新实例
  • 简洁的界面
  • 适用于 TypeScript 和纯 JS
  • 内置 JSON Schema 转换
  • 广泛的生态系统

安装

🌐 Installation

npm install zod

Zod 也可以在 jsr.io 上作为 @zod/zod 使用。

Zod 提供了一个 MCP 服务器,代理可以用它来搜索 Zod 的文档。要将其添加到你的编辑器,请按照这些说明操作。Zod 还提供了一个 llms.txt 文件。

🌐 Zod provides an MCP server that can be used by agents to search Zod's docs. To add to your editor, follow these instructions. Zod also provides an llms.txt file.

要求

🌐 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
  }
}

生态系统

🌐 Ecosystem

Zod 拥有一个繁荣的库、工具和集成生态系统。请参阅Ecosystem 页面获取支持 Zod 或基于其构建的完整库列表。

🌐 Zod has a thriving ecosystem of libraries, tools, and integrations. Refer to the Ecosystem page for a complete list of libraries that support Zod or are built on top of it.

我还为以下项目做出了贡献,我想重点介绍一下:

🌐 I also contribute to the following projects, which I'd like to highlight:

  • tRPC - 端到端类型安全的 API,支持 Zod 模式
  • React Hook Form - 基于 Hook 的表单验证,使用 Zod 解析器
  • zshy - 最初作为 Zod 的内部构建工具创建。无需打包器,自带功能的 TypeScript 库构建工具。由 tsc 提供支持。

On this page