-
Recently I really needed a method for import * as z from "zod";
function zodUnionExtend<
Us extends [z.AnyZodObject, z.AnyZodObject, ...z.AnyZodObject[]],
S extends z.ZodRawShape
>(
union: z.ZodUnion<Us>,
shape: S
): z.ZodUnion<{
[K in keyof Us]: z.ZodObject<
z.objectUtil.extendShape<Us[K]["shape"], S>,
Us[K]["_def"]["unknownKeys"],
Us[K]["_def"]["catchall"]
>;
}> {
/* eslint-disable-next-line @typescript-eslint/ban-ts-comment */
// @ts-ignore
return z.union(union.options.map((o) => o.extend(shape)));
} I tried getting return type of |
Beta Was this translation helpful? Give feedback.
Answered by
mmvsk
Apr 22, 2023
Replies: 1 comment 1 reply
-
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 {
return {
...shape,
...position,
};
} |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
JacobWeisenburger
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use ZodIntersection: