zod icon indicating copy to clipboard operation
zod copied to clipboard

.passthrough() pass through excess nested properties as well

Open MrDrewShep opened this issue 1 year ago • 5 comments

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:

  1. .pick() allow picking and choosing for nested props

MrDrewShep avatar Aug 14 '23 21:08 MrDrewShep

+1

carmelneta avatar Aug 17 '23 10:08 carmelneta

.passthrough() is intended to only work shallowly.

For Zod 4 I'm exploring a way to set the object strictness setting globally.

colinhacks avatar Aug 17 '23 19:08 colinhacks

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

robogeek avatar Dec 06 '23 16:12 robogeek

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.

paul-uz avatar Apr 04 '24 08:04 paul-uz

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?

RomanBaiocco avatar Aug 23 '24 23:08 RomanBaiocco