Skip to content

基础用法

定义 Zod Schema

ts
import * as z from "zod/v4";

// 定义 Zod Schema
const Player = z.object({
  username: z.string(),
  xp: z.number(),
});

const source = { username: "billie", xp: 100 };

// 使用 parse 方法验证数据
const result = Player.parse(source);
console.log(result);
// { username: 'billie', xp: 100 }

// result 是 source 的深拷贝
console.log("result === source", result === source);

使用方式 1

ts
const Player = z.object({
  username: z.string(),
  xp: z.number(),
});

try {
  Player.parse({ username: 42, xp: "100" });
} catch (error) {
  if (error instanceof z.ZodError) {
    console.log(error.issues);
  }
}

error.issues 的内容为

ts
[
  {
    expected: "string",
    code: "invalid_type",
    path: ["username"],
    message: "无效输入:期望 string,实际接收 数字",
  },
  {
    expected: "number",
    code: "invalid_type",
    path: ["xp"],
    message: "无效输入:期望 数字,实际接收 string",
  },
];

使用方式 2 safeParse

除了 try catch 还可以使用 safeParse

ts
const result = Player.safeParse({ username: 42, xp: "100" });

result 的结果:

ts
{
  success: false,
  error: ZodError: [
    {
      "expected": "string",
      "code": "invalid_type",
      "path": [
        "username"
      ],
      "message": "无效输入:期望 string,实际接收 数字"
    },
    {
      "expected": "number",
      "code": "invalid_type",
      "path": [
        "xp"
      ],
      "message": "无效输入:期望 数字,实际接收 string"
    }
  ]
}
ts
{ success: true, data: { username: 'billie', xp: 100 } }