Zod logo

基本用法

本页面将引导你了解创建模式、解析数据和使用推断类型的基础知识。有关 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.

import { z } from "zod/v4"; 
 
const Player = z.object({ 
  username: z.string(),
  xp: z.number()
});

解析数据

¥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.

Player.parse({ username: "billie", xp: 100 }); 
// => returns { username: "billie", xp: 100 }

注意 — 如果你的架构使用某些异步 API,例如 asyncrefinementstransforms,则需要改用 .parseAsync() 方法。

¥Note — If your schema uses certain asynchronous APIs like async refinements or transforms, you'll need to use the .parseAsync() method instead.

const schema = z.string().refine(async (val) => val.length <= 8);
 
await schema.parseAsync("hello");
// => "hello"

错误处理

¥Handling errors

当验证失败时,.parse() 方法将抛出一个 ZodError 实例,其中包含有关验证问题的详细信息。

¥When validation fails, the .parse() method will throw a ZodError instance with granular information about the validation issues.

try {
  Player.parse({ username: 42, xp: "100" });
} catch(err){
  if(error instanceof z.ZodError){
    err.issues; 
    /* [
      {
        expected: 'string',
        code: 'invalid_type',
        path: [ 'username' ],
        message: 'Invalid input: expected string'
      },
      {
        expected: 'number',
        code: 'invalid_type',
        path: [ 'xp' ],
        message: 'Invalid input: expected number'
      }
    ] */
  }
}

要避免 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.

const result = Player.safeParse({ username: 42, xp: "100" });
if (!result.success) {
  result.error;   // ZodError instance
} else {
  result.data;    // { username: string; xp: number }
}

注意 — 如果你的架构使用某些异步 API,例如 asyncrefinementstransforms,则需要改用 .safeParseAsync() 方法。

¥Note — If your schema uses certain asynchronous APIs like async refinements or transforms, you'll need to use the .safeParseAsync() method instead.

const schema = z.string().refine(async (val) => val.length <= 8);
 
await schema.safeParseAsync("hello");
// => { success: true; data: "hello" }

推断类型

¥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.

const Player = z.object({ 
  username: z.string(),
  xp: z.number()
});
 
// extract the inferred type
type Player = z.infer<typeof Player>;
 
// use it in your code
const player: Player = { username: "billie", xp: 100 };

在某些情况下,模式的输入和输出类型可能会有所不同。例如,.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:

const mySchema = z.string().transform((val) => val.length);
 
type MySchemaIn = z.input<typeof mySchema>;
// => string
 
type MySchemaOut = z.output<typeof mySchema>; // equivalent to z.infer<typeof mySchema>
// number

现在我们已经了解了基础知识,让我们开始学习 Schema API。

¥Now that we have the basics covered, let's jump into the Schema API.

On this page