-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
.nullable and .default #425
Comments
Like you said there's no way to do this right now. I think I'm going to introduce a "preprocess" method that would let you attach logic like this to your schema prior to parsing, something like this: const PaginationInputSpec = z
.object({
page: z.number().default(1),
perPage: z.number().default(100),
})
.preprocess((val: unknown) => {
return val ?? {};
}) But for now the best way is to duplicatively define your defaults: const PaginationInputSpec = z
.object({
page: z.number().default(1),
perPage: z.number().default(100),
})
.nullable()
.default({})
.transform((val) => {
return val ?? { page: 1, perPage: 100 };
}); |
Yes, ended up doing exactly that 😄 |
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions. |
EDIT: I see in #421 (comment) it's not actually supposed to work this way... In which case I request that a "default() for nulls" or "default() handles nulls" be added, since I cannot figure out a way to do this without removing the null before passing to zod.
(Using 3.0.0-beta.1)
I expect
.nullable().default(...)
to not havexxx | null
in the output type, in the same way that (redundancy aside).optional().default(...)
does not havexxx | undefined
, but I'm not 100% sure my reasoning is correct.Should
.default()
replacenull
values, so thatnumber().nullable().default(1) => number
ornumber | null
?Or does
.default()
only operate onundefined
s?Should the chaining order matter so that
number().nullable().default(1) => number
andnumber().default(1).nullable() => number | null
?Example:
Is this a bug?
I can try to work around it with:
which removes the
| null
from the output type, but it DOESN'T ACTUALLY WORK AT RUNTIME, making the whole thingundefined
. I expected the "inner" defaults to then take effect, but they don't.Using in a GraphQL API where input optionals can be entirely missing (
undefined
) or explicitlynull
.The text was updated successfully, but these errors were encountered: