How can I allow `null` as input value of a schema, but not as a valid output?
See original GitHub issueI’m trying to use zod
and react-hook-form
together, and find it a bit difficult to deal setting defaultValues
in a way that makes both react-hook-form
, typescript
and the actual schema validation happy.
Say you have this schema:
const zodSchema = z.number().int().nonnegative()
type ZodValues = z.input<typeof zodSchema>
// number <-- want null to be allowed here
type ZodValid = z.output<typeof zodSchema>
// number
Here both ZodValues
and ZodValid
does not allow null
as a value.
If I add nullable
, we get this:
const zodSchema = z.number().int().nonnegative().nullable()
type ZodValues = z.input<typeof zodSchema>
// number | null
type ZodValid = z.output<typeof zodSchema>
// number | null // <-- don't want null to be allowed here
Using yup@0.32.11
(latest now), it seems I’m able to do it like this, which is what I want:
const yupSchema = number().nullable(true).required().integer().min(0)
type YupValues = TypeOf<typeof yupSchema>
// number | null | undefined
type YupValid = Asserts<typeof yupSchema>
// number
Is there any way I can write this schema with zod
, so that the input allows null
, while the output does not?
The issue is that react-hook-form
preferably wants non-undefined default values for the input, and for e.g. number
and Date
inputs I’d really prefer to use null
as I do not want to pick a random number or date to use as the default.
Issue Analytics
- State:
- Created a year ago
- Comments:14
Top GitHub Comments
Discovered the
transform
function gets actx
with anaddIssue
function, so this seems to be a workaround of sorts…That gets correct type, and stops it with a validation issue. Will be quite annoying to have to add that to every nullable number though, haha.
Does
zod
have any way to “extend” it with custom functions? Like, is it possible to add custom stuff to the “chain”, like a.nullNotAllowed()
orcreditCardNumber()
or something like that?Yeah, I think maybe that’s the crux of the issue: the two types describes valid inputs and valid outputs. It doesn’t describe the domain of expected inputs that might be sent (that is
unknown
really).For my purposes, I don’t care that much about the type of the form state since forms have a very loose set of data structures compared to my much more restricted domain model. Whatever works is fine and I trust that the schema does the right thing in all of the situations such that I can “trust” the parsed output. Does that make sense? I don’t know how that squares with the various form libraries, though.