简介


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.
特性
¥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
Zod 还会在每次提交时发布一个预览版本。要安装预览版测试:
¥Zod also publishes a canary version on every commit. To install the canary:
要求
¥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.
"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"
生态系统
¥Ecosystem
Zod 拥有蓬勃发展的库、工具和集成生态系统。请参阅 生态系统页面,获取支持 Zod 或基于 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 模式
¥tRPC - End-to-end typesafe APIs, with support for Zod schemas
-
React Hook Form - 使用 Zod 解析器 进行基于钩子的表单验证
¥React Hook Form - Hook-based form validation with a Zod resolver
-
zshy - 最初是作为 Zod 的内部构建工具创建的。无需打包器、功能齐全的 TypeScript 库构建工具。由
tsc
提供支持。¥zshy - Originally created as Zod's internal build tool. Bundler-free, batteries-included build tool for TypeScript libraries. Powered by
tsc
.