💎 Zod 4 is now stable!  Read the announcement.
Zod logo

基本用法

本頁將引導您了解創建架構、解析數據和使用推斷類型的基礎知識。有關 Zod 架構 API 的完整文檔,請參閱 定義架構

定義架構

在做任何其他事情之前,您需要定義一個架構。為了本指南的目的,我們將使用一個簡單的對象架構。

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

解析數據

給定任何 Zod 架構,請使用 .parse 來驗證輸入。如果有效,Zod 將返回輸入的強類型 深度克隆

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

注意 — 如果您的架構使用某些異步 API,如 async 細化轉換,您需要改用 .parseAsync() 方法。

await Player.parseAsync({ username: "billie", xp: 100 }); 

處理錯誤

當驗證失敗時,.parse() 方法將拋出一個 ZodError 實例,其中包含有關驗證問題的詳細信息。

try {
  Player.parse({ username: 42, xp: "100" });
} catch(error){
  if(error instanceof z.ZodError){
    error.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 的純結果對象。結果類型是一個 判別聯合,因此您可以方便地處理這兩種情況。

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

注意 — 如果您的架構使用某些異步 API,如 async 細化轉換,您需要改用 .safeParseAsync() 方法。

await schema.safeParseAsync("hello");

推斷類型

Zod 從您的架構定義中推斷靜態類型。您可以使用 z.infer<> 工具提取此類型,並隨意使用它。

const Player = z.object({ 
  username: z.string(),
  xp: z.number()
});
 
// 提取推斷類型
type Player = z.infer<typeof Player>;
 
// 在您的代碼中使用它
const player: Player = { username: "billie", xp: 100 };

在某些情況下,架構的輸入和輸出類型可能會有所不同。例如,.transform() API 可以將輸入從一種類型轉換為另一種類型。在這些情況下,您可以獨立提取輸入和輸出類型:

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

現在我們已經涵蓋了基礎知識,讓我們跳轉到 架構 API。

On this page