colinhacks/zod

We should not allow `optional`, `nullish`, or `nullable` on `z.coerce` schemas

scotttrinh opened this issue · 1 comments

Since z.coerce.* schemas will always return the primitive, even if you pass undefined or null, we should disallow this. Also, things like z.union([z.coerce.string(), z.coerce.number()]) will always return a string since the first schema will just always succeed.

Those methods wrap the existing schema with ZodOptional, ZodNullable, or both. So optionality still worked as intended, and the coercion behavior doesn't "bubble up"

z.coerce.string().optional().parse(undefined)
// => undefined

It's true that a coerced schema will never throw, so .catch() is a no-op. But tbh I don't much care about no ops. We could override these methods on certain subclasses to throw an error, or mark them with strikethrough using @deprecated. But I think that would introduce more confusion than it resolves.