colinhacks / zod

TypeScript-first schema validation with static type inference
https://zod.dev
MIT License
33.58k stars 1.16k forks source link

.passthrough() pass through excess nested properties as well #2655

Open MrDrewShep opened 1 year ago

MrDrewShep commented 1 year ago

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
carmelneta commented 1 year ago

+1

colinhacks commented 1 year ago

.passthrough() is intended to only work shallowly.

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

robogeek commented 10 months ago

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

paul-uz commented 6 months ago

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.

RomanBaiocco commented 1 month ago

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?