Skip to content

类型(上)

https://zod.zhcndoc.com/api

示例 01

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

const Player = z.object({
  account: z.string(),
});

const data = Player.safeParse({ account: 1 });

console.log(data);

会得到:

json
 {
  success: false,
  error: ZodError: [
    {
      "expected": "string",
      "code": "invalid_type",
      "path": [
        "account"
      ],
      "message": "Invalid input: expected string, received number"
    }
  ]
 }

可选

可选只是允许 undefined

ts
z.string().optional();

可空

可空只是允许 null

ts
z.string().nullable();

可选可空

ts
z.string().nullish();

never

任意类型

强制类型转换

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

const Player = z.object({
  account: z.coerce.string(),
});

const data = Player.safeParse({ account: 1 });

console.log(data);

会得到:

js
{ success: true, data: { account: '1' } }

强制转换的原理:String(value)Number(value)Boolean(value)new Date(value)BigInt(value)

在强制转换 boolean 时候需要特别注意

ts
const schema = z.coerce.boolean(); // Boolean(input)

schema.parse("tuna"); // => true
schema.parse("true"); // => true
schema.parse("false"); // => true
schema.parse(1); // => true
schema.parse([]); // => true

schema.parse(0); // => false
schema.parse(""); // => false
schema.parse(undefined); // => false
schema.parse(null); // => false

字面量类型

ts
account: z.literal("tom");
account: z.literal(["tom", "jerry"]);

account 只能是 tom 或者 jerry

string

验证

ts
z.string().max(5);
z.string().min(5);
z.string().length(5);
z.string().regex(/^[a-z]+$/);
z.string().startsWith("aaa");
z.string().endsWith("zzz");
z.string().includes("---");

转换

ts
z.string().trim(); // 去除空白
z.string().toLowerCase(); // 转小写
z.string().toUpperCase(); // 转大写

验证封装

zod 的验证非常严格,用的时候需要注意

ts
z.email();

// 支持 "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8"
z.uuid({ version: "v4" });

// 方便形式
z.uuidv4();
z.uuidv6();
z.uuidv7();

z.url();
z.emoji(); // 验证单个 emoji 字符
z.base64();
z.base64url();
z.nanoid();
z.cuid();
z.cuid2();
z.ulid();
z.ipv4();
z.ipv6();
z.cidrv4(); // ipv4 CIDR 块
z.cidrv6(); // ipv6 CIDR 块

z.iso.date(); // YYYY-MM-DD
z.iso.time(); // HH:MM[:SS[.s+]]
z.iso.datetime(); // 方法强制 ISO 8601 格式;默认不允许时区偏移:
z.iso.duration();

templateLiteral / 模板字符串

todo

ts
const schema = z.templateLiteral(["hello, ", z.string(), "!"]);
// `hello, ${string}!`

number

ts
const schema = z.number();

schema.parse(3.14); // ✅
schema.parse(NaN); // ❌
schema.parse(Infinity); // ❌
ts
z.number().gt(5); // 大于 5
z.number().gte(5); // 同 .min(5)

z.number().lt(5); // 小于 5
z.number().lte(5); // 同 .max(5)

z.number().positive(); // 大于 0
z.number().nonnegative(); // 非负
z.number().negative(); // 小于 0
z.number().nonpositive(); // 小于等于 0

z.number().multipleOf(5); // 同 .step(5),该数必须是 5 的倍数

int

ts
z.int(); // 限制在安全整数范围
z.int32(); // 限制在 int32 范围

bigint

ts
z.bigint();

bigint 有和 number 一样的方法

日期

todo

枚举

todo

字符串布尔值

todo