Built-in way to coerce null to undefined #2103
-
Right now I'm doing something like this: const coerceNullToUndefined = <Type>(value : Type | null | undefined) : Type | undefined => {
return value === null ? undefined : value;
};
const apiResponseSchema = z.object({
name: z.string().nullish().transform(coerceNullToUndefined)
}); That makes the resulting value a little more sane; I don't have to worry about dealing with both null and undefined. It would be awesome if it was possible to have a built-in way to do this, like: const apiResponseSchema = z.object({
name: z.string().nullish().coerceNullToUndefined()
}); |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 4 replies
-
A little cleaner way to do this is: const schema = z.string().nullish().transform( x => x ?? undefined )
type Data = z.infer<typeof schema>
// type Data = string | undefined
console.log( schema.parse( 'foo' ) ) // 'foo'
console.log( schema.parse( null ) ) // undefined
console.log( schema.parse( undefined ) ) // undefined Because this is quite a simple and clean way to do this. I'm not sure we need a built-in way to do this. Thoughts? |
Beta Was this translation helpful? Give feedback.
-
I think we need a built-in way to coerce it from "unknown" values. |
Beta Was this translation helpful? Give feedback.
-
Something built-in like |
Beta Was this translation helpful? Give feedback.
A little cleaner way to do this is:
Because this is quite a simple and clean way to do this. I'm not sure we need a built-in way to do this. Thoughts?