Promises
ts
const numberPromise = z.promise(z.number());const numberPromise = z.promise(z.number());"Parsing" works a little differently with promise schemas. Validation happens in two parts:
- Zod synchronously checks that the input is an instance of Promise (i.e. an object with
.thenand.catchmethods.). - Zod uses
.thento attach an additional validation step onto the existing Promise. You'll have to use.catchon the returned Promise to handle validation failures.
ts
numberPromise.parse("tuna");
// ZodError: Non-Promise type: string
numberPromise.parse(Promise.resolve("tuna"));
// => Promise<number>
const test = async () => {
await numberPromise.parse(Promise.resolve("tuna"));
// ZodError: Non-number type: string
await numberPromise.parse(Promise.resolve(3.14));
// => 3.14
};numberPromise.parse("tuna");
// ZodError: Non-Promise type: string
numberPromise.parse(Promise.resolve("tuna"));
// => Promise<number>
const test = async () => {
await numberPromise.parse(Promise.resolve("tuna"));
// ZodError: Non-number type: string
await numberPromise.parse(Promise.resolve(3.14));
// => 3.14
};