Promises
Zod provides functionality for validating Promises.
Basic Usage
ts
import { z } from "zod";
// Create a Promise schema
const PromiseString = z.promise(z.string());
type PromiseString = z.infer<typeof PromiseString>; // Promise<string>
// Validation
PromiseString.parse(Promise.resolve("hello")); // passes
PromiseString.parse(Promise.resolve(123)); // fails
PromiseString.parse("hello"); // fails: not a Promise
Async Validation
Use .parseAsync()
to validate Promises:
ts
const schema = z.promise(z.string());
// Using async/await
async function validate() {
const result = await schema.parseAsync(Promise.resolve("hello"));
console.log(result); // "hello"
}
// Using Promise chains
schema
.parseAsync(Promise.resolve("hello"))
.then(result => console.log(result))
.catch(error => console.error(error));
Complex Promise Types
Promises can contain any Zod schema:
ts
// Promise of an object
const UserPromise = z.promise(
z.object({
id: z.number(),
name: z.string(),
})
);
// Promise of an array
const ArrayPromise = z.promise(z.array(z.string()));
// Promise of a union type
const UnionPromise = z.promise(
z.union([z.string(), z.number()])
);
Error Handling
Handle errors in Promise validation:
ts
const schema = z.promise(z.string());
try {
await schema.parseAsync(Promise.reject(new Error("Something went wrong")));
} catch (error) {
console.error("Validation failed:", error);
}
// Custom error messages
const customSchema = z.promise(
z.string({
invalid_type_error: "Value must be a string",
})
);
Promise Chains
Validate values in Promise chains:
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));
Type Inference
TypeScript can correctly infer Promise types:
ts
const schema = z.promise(
z.object({
name: z.string(),
age: z.number(),
})
);
type PromiseType = z.infer<typeof schema>;
// Promise<{ name: string; age: number }>
// Using the type
async function fetchUser(): PromiseType {
return Promise.resolve({
name: "John Doe",
age: 25,
});
}