Lesson
Define Unions and Intersections with Zod
implement unions and intersections in Zod schemas for example domain related objects, enhancing TypeScript validation with clear examples
- Access
- Included
- Transcript
- Needs source
In this lesson we'll use a few predefined schemas which will serve as constituents to create union and intersection schemas.
Three room booking schemas are defined: single, double, and suite. Each schema has slight differences in the structure.
The z.union utility is used to create a union of these schemas, allowing for validation against any of them. Type inference (using z.infer) for the room booking schema produces a union of object literals, exactly like in TypeScript.
We also create an intersection using z.intersection, combining room booking details with discount information.
These techniques enhance data validation and allow to make zod aligned even more with TypeScript.