Skip to content

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

Discussion options

You must be logged in to vote

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

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by JacobWeisenburger
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants
Converted from issue

This discussion was converted from issue #2052 on February 17, 2023 16:38.