Intersections
Intersections are useful for creating "logical AND" types. This is useful for intersecting two object types.
ts
const Person = z.object({
name: z.string(),
});
const Employee = z.object({
role: z.string(),
});
const EmployedPerson = z.intersection(Person, Employee);
// equivalent to:
const EmployedPerson = Person.and(Employee);
const Person = z.object({
name: z.string(),
});
const Employee = z.object({
role: z.string(),
});
const EmployedPerson = z.intersection(Person, Employee);
// equivalent to:
const EmployedPerson = Person.and(Employee);
Though in many cases, it is recommended to use A.merge(B)
to merge two objects. The .merge
method returns a new ZodObject
instance, whereas A.and(B)
returns a less useful ZodIntersection
instance that lacks common object methods like pick
and omit
.
ts
const a = z.union([z.number(), z.string()]);
const b = z.union([z.number(), z.boolean()]);
const c = z.intersection(a, b);
type c = z.infer<typeof c>; // => number
const a = z.union([z.number(), z.string()]);
const b = z.union([z.number(), z.boolean()]);
const c = z.intersection(a, b);
type c = z.infer<typeof c>; // => number