Whimsy - .optional() makes the type optional? l...
.optional() makes the type optional? like using it with
z.boolean().default(false)
makes it boolean | undefined
4 Replies
you don't need to use
.optional
when using .default
@Whimsyoptional
is like ?: T | undefined
and default
is like object destructuring with default. Note that "it" is different between the input type and output type for default
since the input type is T | undefined
and the output type is just T
(which is the point of default
)Yeah on the Output type that is.
.optional()
allows undefined
to be inputted, and outputs undefined
for that value.
.default(value)
allows undefined
to be inputted, and outputs typeof value
for that value.
So z.boolean().default(false
makes the input type boolean | undefined
and the output type boolean
while z.boolean.optional()
makes both boolean | undefined
.
You can see that here:
https://github.com/colinhacks/zod/blob/main/src/types.ts#L4637
https://github.com/colinhacks/zod/blob/main/src/types.ts#L4724
In the codebase it is even more explicitly stated: The output can never be undefined when using .default()
yeah that's what i was asking