基本用法
本页面将引导你了解创建模式、解析数据和使用推断类型的基础知识。有关 Zod 架构 API 的完整文档,请参阅 定义模式。
¥This page will walk you through the basics of creating schemas, parsing data, and using inferred types. For complete documentation on Zod's schema API, refer to Defining schemas.
定义模式
¥Defining a schema
在执行其他任何操作之前,你需要定义一个 Schema。出于本指南的目的,我们将使用一个简单的对象模式。
¥Before you can do anything else, you need to define a schema. For the purposes of this guide, we'll use a simple object schema.
解析数据
¥Parsing data
对于任何 Zod 模式,使用 .parse
来验证输入。如果有效,Zod 将返回输入的强类型深度克隆。
¥Given any Zod schema, use .parse
to validate an input. If it's valid, Zod returns a strongly-typed deep clone of the input.
注意 — 如果你的架构使用某些异步 API,例如 async
、refinements 或 transforms,则需要改用 .parseAsync()
方法。
¥Note — If your schema uses certain asynchronous APIs like async
refinements or transforms, you'll need to use the .parseAsync()
method instead.
错误处理
¥Handling errors
当验证失败时,.parse()
方法将抛出一个 ZodError
实例,其中包含有关验证问题的详细信息。
¥When validation fails, the .parse()
method will throw a ZodError
instance with granular information about the validation issues.
要避免 try/catch
阻塞,你可以使用 .safeParse()
方法返回包含成功解析数据或 ZodError
的纯文本结果对象。结果类型为 可区分联合,因此你可以方便地处理这两种情况。
¥To avoid a try/catch
block, you can use the .safeParse()
method to get back a plain result object containing either the successfully parsed data or a ZodError
. The result type is a discriminated union, so you can handle both cases conveniently.
注意 — 如果你的架构使用某些异步 API,例如 async
、refinements 或 transforms,则需要改用 .safeParseAsync()
方法。
¥Note — If your schema uses certain asynchronous APIs like async
refinements or transforms, you'll need to use the .safeParseAsync()
method instead.
推断类型
¥Inferring types
Zod 会根据你的模式定义推断出静态类型。你可以使用 z.infer<>
实用程序提取此类型,并根据需要使用它。
¥Zod infers a static type from your schema definitions. You can extract this type with the z.infer<>
utility and use it however you like.
在某些情况下,模式的输入和输出类型可能会有所不同。例如,.transform()
API 可以将输入从一种类型转换为另一种类型。在这些情况下,你可以分别提取输入和输出类型:
¥In some cases, the input & output types of a schema can diverge. For instance, the .transform()
API can convert the input from one type to another. In these cases, you can extract the input and output types independently:
现在我们已经了解了基础知识,让我们开始学习 Schema API。
¥Now that we have the basics covered, let's jump into the Schema API.