Skip to content

原始类型

ts
import * as z from "zod";

// 原始类型
z.string();
z.number();
z.bigint();
z.boolean();
z.symbol();
z.undefined();
z.null();
ts
import * as z from "zod";

const schema = z.string();

schema.parse("tuna"); // => "tuna"
schema.parse(42); // 报错

coerce / 类型强制转换

ts
const schema = z.coerce.string();

schema.parse("tuna"); // => "tuna"
schema.parse(42); // => "42"
schema.parse(true); // => "true"
schema.parse(null); // => "null"

不会报错,并且会强制类型转换

使用 coerce 先看看文档

其转换可能不会如你所愿

https://zod.zhcndoc.com/api?id=强制转换