How to have .optional() survive during transform() #3299
-
How would I keep a property as truly optional ( Take the example below, the property is correctly inferred as optional (
|
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
Is this what you are looking for? const objectA = z.object( { a: z.number().optional() } )
type A = z.infer<typeof objectA>
// type A = { a?: number | undefined }
const objectB = z.object( { a: z.number().optional() } ).transform( ( x ) => {
const a = x.a?.toString()
if ( a ) return { a }
return {}
} )
type B = z.infer<typeof objectB>
// type B = { a: string } | { a?: undefined } 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! Yes, that's technically the result I want..but I'm not clear about the way to get there outside of this simple example. I'm transforming many properties at once, some of which may be undefined. How would I do this with many properties?
|
Beta Was this translation helpful? Give feedback.
-
In |
Beta Was this translation helpful? Give feedback.
In
zod
, an optional property means that it could beundefined
. I understand that it is confusing, because in typescriptundefined
and optional are 2 similar things, but not the same.