zod
zod copied to clipboard
.passthrough() pass through excess nested properties as well
Appears .passthrough()
only operates on root properties.
import { z } from 'zod';
const schema = z.object({
first: z.string(),
details: z.object({
hair: z.string(),
}),
});
const myObj = {
first: 'me',
last: 'mine',
details: {
hair: 'red',
eyes: 'blue',
},
};
const res = schema.passthrough().safeParse(myObj);
console.log(res);
Actual results
{
success: true,
data: { first: 'me', details: { hair: 'red' }, last: 'mine' }
}
Expected results
{
success: true,
data: { first: 'me', details: { hair: 'red', eyes: 'blue' }, last: 'mine' }
}
Additional functionality which would be very handy, as it relates to nested properties:
-
.pick()
allow picking and choosing for nested props
+1
.passthrough()
is intended to only work shallowly.
For Zod 4 I'm exploring a way to set the object strictness setting globally.
I have the same issue.
I'm working on data types generated from an OpenAPI-based API that has many nested objects. The API specification explicitly allows implementors to add additional properties on mutual agreement. That means data validation must do what passthrough does, which is to check the things defined in the API spec but pass everything else through.
But, as noted above, for nested objects passthrough
does not apply. Additional fields are not passed through.
With Joi, I get the desired effect this way:
joiIsEvent.validate(data, {
allowUnknown: true
})
Where joiIsEvent
was defined using Joi declarations.
Hence, if zodSchema.parse()
took an optional options argument with this value - as you say, a strictness setting that's handled "globally" ...
How can I get around this current limitation? I need to have a nested object with one specific rule, and then allow other fields, without knowing what they are beforehand.
Hey @colinhacks!
With Zod 4 in active development, I was wondering if the global object strictness setting you mentioned is planned to be included in the upcoming release?