Merging into a schema that accepts "any type of these 3" is done by a union of the three types, using ….or(…) or z.union(…). However, since those types are to be distinguished based on their attachmentType, you really want a discriminated union which will make checking more efficient:
const postSchema = z.discriminatedUnion("attachmentType", [
imagePostSchema,
videoPostSchema,
textPostSchema,
]);
Answer from Bergi on Stack OverflowMerging into a schema that accepts "any type of these 3" is done by a union of the three types, using ….or(…) or z.union(…). However, since those types are to be distinguished based on their attachmentType, you really want a discriminated union which will make checking more efficient:
const postSchema = z.discriminatedUnion("attachmentType", [
imagePostSchema,
videoPostSchema,
textPostSchema,
]);
you can create a new Schema by combining all of them in to a single One by spreading those schemas in to the new one
export const formSchema = z.object({
...imagePostSchema.shape,
...videoPostSchema.shape,
...textPostSchema.shape,
});
Run code snippetEdit code snippet Hide Results Copy to answer Expand
How to combine form zod schemas
How to union or merge two or more z.record schemas
How do I merge two Zod schemas?
Calling `.merge` or `.extend` on recursive types
Hey guys, I’m just a little stumped on how to go about this properly.
I’m using react hook form with zod resolvers and want to make a single form that can do both update and create actions.
I have 2 separate zod schemas for update and create, how do I conditionally handle this scenario.
Thanks all !