Skip to content

.extend on a ZodUnion of objects #2279

Answered by mmvsk
rijenkii asked this question in Q&A
Discussion options

You must be logged in to vote

Use ZodIntersection:

const CircleSchema = Z.object({
    radius: Z.number(),
});

const RectangleSchema = Z.object({
    sideA: Z.number(),
    sideB: Z.number(),
});

const ShapeSchema = Z.discriminatedUnion("type", [
    CircleSchema.extend({ type: Z.literal("circle") }),
    RectangleSchema.extend({ type: Z.literal("rectangle") }),
]);

const PositionSchema = Z.object({ x: Z.number(), y: Z.number() });

const PlanObjectSchema = Z.intersection(ShapeSchema, PositionSchema);

type Shape = Z.output<typeof ShapeSchema>;
type Position = Z.output<typeof PositionSchema>;
type PlanObject = Z.output<typeof PlanObjectSchema>;

function CreatePlanObject(shape: Shape, position: Position): PlanObject {

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@andho
Comment options

Answer selected by JacobWeisenburger
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants