zod icon indicating copy to clipboard operation
zod copied to clipboard

Intersections can result in duplicate errors

Open rjmackay opened this issue 2 years ago • 2 comments

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)

rjmackay avatar Jul 06 '23 03:07 rjmackay

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() 
});

krs-10 avatar Nov 02 '23 14:11 krs-10

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).

mkdior avatar Mar 04 '24 08:03 mkdior