-
-
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
Standardize behavior of optionals + defaults #421
Conversation
No opinion
No opinion
Seems good as long as you don't have to pass a Are you doing a Can this also
Nice.
You know I love this (#403) Overall, great changes 👏 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Looks fantastic, can't wait to use .nullish
! 🚀
Glad you like it :) I was planning to just implement Currently defaults are only applied when the schema receives an Regarding the base-class convenience method, this could be introduced as a new method ( |
@colinhacks If a new method will be added ( |
@colinhacks +1 for a I'm running into some impedance mismatches between Zod and React Hook Forms with regards to undefined / null handling. RHF discourages the use of Setting the field as |
1. Default values are now implemented in separate
ZodDefault
class.Previously this logic was folded into ZodOptional.
2. Standardized behavior of
.optional()
and.nullable()
methods.Previously calling
.optional()
on an instance of ZodOptional instance would return the current instance instead of redundantly nesting ZodOptional instances. This seems entirely unnecessary, feels too magical, and introduced complexity into the typings. This complexity makes it harder to write generic functions on top of Zod: #355 (comment)3. No
undefined
defaultsThere's no point in setting
undefined
value as a default value, it's a NOOP. This also lets us explicitly eliminate optionals from the inferred output types of ZodDefault:4. Calls to
.optional
always return schema withT | undefined
This is a consequence of #2. Previously calling
.optional()
onz.string().default()
would return the instance unchanged, since defaults values were implemented in the ZodOptional class. Now it introduces a new ZodOptional instance that wraps a ZodDefault instance. As such the type signature is nowstring | undefined
instead ofstring
.This introduces a nice duality into chained calls to
default
andoptional
.5. Introduce .nullish()