Skip to content

基本用法

使用中文包

ts
import * as z from "zod/v4";
// import { z } from "zod/v4";
import zhCN from "zod/v4/locales/zh-CN.js";

z.config(zhCN());

基础用法 01

sh
import { z } from "zod/v4";

const Player = z.object({
  account: z.string({ error: "账号不能为空" }),
  password: z.string({ error: "密码不能为空" }),
  invitationCode: z.string({ error: "邀请码不能为空" }),
});

const data = Player.parse({});

解析会报错:

json
ZodError: [
  {
    "expected": "string",
    "code": "invalid_type",
    "path": [
      "account"
    ],
    "message": "账号不能为空"
  },
  {
    "expected": "string",
    "code": "invalid_type",
    "path": [
      "password"
    ],
    "message": "密码不能为空"
  },
  {
    "expected": "string",
    "code": "invalid_type",
    "path": [
      "invitationCode"
    ],
    "message": "邀请码不能为空"
  }
]

如何处理报错,

  1. try catch
  2. 使用 safeParse
ts
const data = Player.safeParse({});

console.log(data);

输出:

json
 {
  success: false,
  error: ZodError: [
    {
      "expected": "string",
      "code": "invalid_type",
      "path": [
        "account"
      ],
      "message": "账号不能为空"
    },
    {
      "expected": "string",
      "code": "invalid_type",
      "path": [
        "password"
      ],
      "message": "密码不能为空"
    },
    {
      "expected": "string",
      "code": "invalid_type",
      "path": [
        "invitationCode"
      ],
      "message": "邀请码不能为空"
    }
  ]

推断类型

提取所定义的 schema 的 ts 类型

ts
type Player = z.infer<typeof Player>;

类型不一致时

todo

ts
const mySchema = z.string().transform((val) => val.length);

type MySchemaIn = z.input<typeof mySchema>;
// => string

type MySchemaOut = z.output<typeof mySchema>; // 等同于 z.infer<typeof mySchema>
// number