Open dhruvsaxena1998 opened 3 weeks ago
The diff when default or optional function call is removed from schema
"example": {
"issues": [
{
"code": "invalid_type",
"expected": "number",
"received": "nan",
"path": [
"limit"
],
"message": "Expected number, received nan"
}
],
"name": "ZodError"
}
Hey! 👋
The difference you're seeing is due to the default or optional behavior in Zod. When limit is set as optional or has a default value, the schema treats it as optional in the OpenAPI spec. This means if the limit parameter is missing, the request still goes through with the default value (10), and validation errors are simpler.
However, when you remove default or optional, the schema treats limit as required. This changes the OpenAPI spec to show required: true, meaning limit must be provided in the request. If limit is missing or invalid, Zod provides more detailed error messages (like expected: "number", received: "nan") to specify what went wrong, making it clearer for debugging. Potential Solutions
If you want limit to be optional but still include detailed error messages, you could:
Set a default value and add custom error handling to log detailed messages when validation fails.
Consider using refine() in Zod to control the error message while still providing default values.
Hope this clarifies the difference! 😊
Code
This Generates below JSON
On the other hand if default / optional is removed from the schema