.omit() inoperative with .passthrough() #2055
-
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
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
https://github.com/colinhacks/zod#pickomit 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! 🙏 |
Beta Was this translation helpful? Give feedback.
-
Thanks, that's what I did on the last line of my code above. It indeed makes sense from the schema point of view, but it's not intuitive and kind of misleading when the methods are in the following order:
There On the other hand, I didn't expect a transformation from Having However, Thanks again for your time. |
Beta Was this translation helpful? Give feedback.
https://github.com/colinhacks/zod#pickomit
.omit
omits keys from the schema, not from the parsed/validated data. Therefore it makesb
an unknown key, thus causing it to be passed through.This is the way that I would do what you are trying to do:
If you found my answer satisfactory, please consider supporting me. Even a small amount is greatly appreciated. Thanks friend! 🙏
https://github.com/sponsors/JacobWeisenburger