Promises
Zod 提供了验证 Promise 的功能。
基本用法
ts
import { z } from "zod";
// 创建 Promise 模式
const PromiseString = z.promise(z.string());
type PromiseString = z.infer<typeof PromiseString>; // Promise<string>
// 验证
PromiseString.parse(Promise.resolve("hello")); // 通过
PromiseString.parse(Promise.resolve(123)); // 失败
PromiseString.parse("hello"); // 失败:不是 Promise
异步验证
使用 .parseAsync()
来验证 Promise:
ts
const schema = z.promise(z.string());
// 使用 async/await
async function validate() {
const result = await schema.parseAsync(Promise.resolve("hello"));
console.log(result); // "hello"
}
// 使用 Promise 链
schema
.parseAsync(Promise.resolve("hello"))
.then(result => console.log(result))
.catch(error => console.error(error));
复杂 Promise 类型
Promise 可以包含任何 Zod 模式:
ts
// Promise 中的对象
const UserPromise = z.promise(
z.object({
id: z.number(),
name: z.string(),
})
);
// Promise 中的数组
const ArrayPromise = z.promise(z.array(z.string()));
// Promise 中的联合类型
const UnionPromise = z.promise(
z.union([z.string(), z.number()])
);
错误处理
处理 Promise 验证中的错误:
ts
const schema = z.promise(z.string());
try {
await schema.parseAsync(Promise.reject(new Error("出错了")));
} catch (error) {
console.error("验证失败:", error);
}
// 自定义错误消息
const customSchema = z.promise(
z.string({
invalid_type_error: "值必须是字符串",
})
);
Promise 链
验证 Promise 链中的值:
ts
const schema = z.promise(z.string());
Promise.resolve(123)
.then(value => value.toString())
.then(async value => {
const result = await schema.parseAsync(Promise.resolve(value));
return result;
})
.catch(error => console.error(error));
类型推断
TypeScript 可以正确推断 Promise 的类型:
ts
const schema = z.promise(
z.object({
name: z.string(),
age: z.number(),
})
);
type PromiseType = z.infer<typeof schema>;
// Promise<{ name: string; age: number }>
// 使用类型
async function fetchUser(): PromiseType {
return Promise.resolve({
name: "张三",
age: 25,
});
}