Closed Tekpakma closed 1 week ago
Thanks for your feedback. I think that optional
, nullable
or nullish
should cover your use case. By providing a default value, the output type is not optional. You can try it out in our playground and read more details in this guide.
Hey Fabian, thanks for the quick reply. I see where you're coming from, but I still think there's a case for adding a default method for parsing required types without interfering with the schema. Let me elaborate with your example:
Currently, I can infer the output or input types from the schema. Considering this structure:
const Schema = v.object({ name: v.optional(v.string(), 'Jane'), age: v.optional(v.number(), 0), job: v.string() });
To get the corresponding type, I would use InferInput. However, parsing will fail if no value is provided for job since it is required.
I want to be enabled tho to handle missing values gracefully without changing the schema definition, which IMO would make the library more flexible (f.e. in scenarios like getDefaultValues :D).
I see your point, but maybe you are misusing the defaults of your schema as the initial values of your form. It might be better to define them separately. Especially for more complex schemas, your approach does not work.
I will close this issue for now.
Yes, forgot to respond. Thanks for your Feedback.
Getting Default Values from a Schema is a common use case, never entirely solved by zod: https://github.com/colinhacks/zod/discussions/2272
Currently, the only way to provide a default Value in valibot, is by using optional. I noticed the deprecation of withDefault, which I don't agree with: https://github.com/fabian-hiller/valibot/issues/96
Especially when using Form Libraries, sometimes I want to provide a default value also for Required Params, without making a Field truly optional. Zod gives the option of using .default here: https://zod.dev/?id=default
This would work greatly together with valibots getDefaults, which would collect the set default, instead of undefined.
This would more or less fluently allow me to get all my Default-Values directly from my Schema.