基本用法
本页面将引导你了解创建模式、解析数据以及使用推断类型的基础知识。有关 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
在你能做其他任何事情之前,你需要定义一个模式。为了本指南的目的,我们将使用一个简单的对象模式。
🌐 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.
错误处理
🌐 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.
推断类型
🌐 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.

