Skip to content

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

.omit() inoperative with .passthrough() #2052

Closed
adrien-febvay opened this issue Feb 17, 2023 · 1 comment
Closed

.omit() inoperative with .passthrough() #2052

adrien-febvay opened this issue Feb 17, 2023 · 1 comment

Comments

@adrien-febvay
Copy link

adrien-febvay commented Feb 17, 2023

.omit() doesn't do anything when using .passthrough(): the omitted keys are still there.

import { z } from 'zod'; // zod@3.20.6

// Our schema, just two known keys `a` and `b`
const schema = z.object({ a: z.number(), b: z.number() });

// We want to omit `b`, but preserve unknown keys
// No luck here: we get { a: 1, b: 2, x: 654 }
console.log(schema.omit({ b: true }).passthrough().parse({ a: 1, b: 2, x: 654 }));

// Still not what we want: { a: 1, b: 2, y: 286 }
console.log(schema.passthrough().omit({ b: true }).parse({ a: 1, b: 2, y: 286 }));

// Workaround for expected result: { a: 1, z: 123 }
console.log(schema.passthrough().transform(({ b, ...res }) => res).parse({ a: 1, b: 2, z: 123 }));

Am I doing something wrong? Am I not supposed to chain those two methods?

I understood that .passthrough() would just pass unknown keys, not omitted ones:

https://www.npmjs.com/package/zod#passthrough
By default Zod object schemas strip out unrecognized keys during parsing.
Instead, if you want to pass through unknown keys, use .passthrough().

@JacobWeisenburger
Copy link
Contributor

https://github.com/colinhacks/zod#pickomit
.omit omits keys from the schema, not from the parsed/validated data. Therefore it makes b an unknown key, thus causing it to be passed through.

This is the way that I would do what you are trying to do:

const schema = z.object( { a: z.number(), b: z.number() } )
    .passthrough()
    .transform( ( { b, ...rest } ) => rest )

console.log( schema.parse( { a: 1, b: 2, z: 123 } ) )
// { a: 1, z: 123 }

If you found my answer satisfactory, please consider supporting me. Even a small amount is greatly appreciated. Thanks friend! 🙏
https://github.com/sponsors/JacobWeisenburger

Repository owner locked and limited conversation to collaborators Feb 17, 2023
@JacobWeisenburger JacobWeisenburger converted this issue into discussion #2055 Feb 17, 2023

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants