zod
zod copied to clipboard
Intersections can result in duplicate errors
An intersection like this
const schema = z
.object({ packageCount: z.coerce.number().optional() })
.and(z.object({ packageCount: z.coerce.number().optional() }))
schema.parse({ packageCount: 'asd' })
will result in 2 invalid_type errors instead of just one.
Obviously this is a contrived example, but I'm doing something like this in real code so that I can apply a refine() to one part of the union (see https://github.com/colinhacks/zod/issues/2524#issuecomment-1622897861)
I'm also observing the same issue using z.intersection (and z.and), and my simplified example is also contrived due to needing to support date refine operations later down the line. The duplicate invalid_type errors are happening with and without refine/superRefine:
const nonDateSchema = z.object({
destination: z.enum(["internal", "external"]),
type: z.string()
});
const dateSchema = z.object({
startDate: z.date(),
endDate: z.date(),
needByDate: z.date()
});
const schema = z.intersection(nonDateSchema, dateSchema);
schema.parse({
destination: "internal",
type: "Foobar",
startDate: new Date(),
endDate: new Date(),
needByDate: new Date()
});
Same thing happening for me. Sadly enough, I don't think there's really a way around this. Before persisting zod issues, I just filter out duplicate objects (doing deep checks).