zod
zod copied to clipboard
`.toJSONSchema()` Fix optional behaviour
https://github.com/colinhacks/zod/issues/4089
.optional() and .nonoptional() shouldn't actually change our type as optionality and nullability are different things.
I've changed it to just pipe through our inner type.
[!IMPORTANT]
Review skipped
Auto reviews are disabled on base/target branches other than the default branch.
Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.You can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.
🪧 Tips
Chat
There are 3 ways to chat with CodeRabbit:
- Review comments: Directly reply to a review comment made by CodeRabbit. Example:
I pushed a fix in commit <commit_id>, please review it.Generate unit testing code for this file.Open a follow-up GitHub issue for this discussion.
- Files and specific lines of code (under the "Files changed" tab): Tag
@coderabbitaiin a new review comment at the desired location with your query. Examples:@coderabbitai generate unit testing code for this file.@coderabbitai modularize this function.
- PR comments: Tag
@coderabbitaiin a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:@coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.@coderabbitai read src/utils.ts and generate unit testing code.@coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.@coderabbitai help me debug CodeRabbit configuration file.
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.
CodeRabbit Commands (Invoked using PR comments)
@coderabbitai pauseto pause the reviews on a PR.@coderabbitai resumeto resume the paused reviews.@coderabbitai reviewto trigger an incremental review. This is useful when automatic reviews are disabled for the repository.@coderabbitai full reviewto do a full review from scratch and review all the files again.@coderabbitai summaryto regenerate the summary of the PR.@coderabbitai generate docstringsto generate docstrings for this PR.@coderabbitai resolveresolve all the CodeRabbit review comments.@coderabbitai planto trigger planning for file edits and PR creation.@coderabbitai configurationto show the current CodeRabbit configuration for the repository.@coderabbitai helpto get help.
Other keywords and placeholders
- Add
@coderabbitai ignoreanywhere in the PR description to prevent this PR from being reviewed. - Add
@coderabbitai summaryto generate the high-level summary at a specific location in the PR description. - Add
@coderabbitaianywhere in the PR title to generate the title automatically.
CodeRabbit Configuration File (.coderabbit.yaml)
- You can programmatically configure CodeRabbit by adding a
.coderabbit.yamlfile to the root of your repository. - Please see the configuration documentation for more information.
- If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation:
# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json
Documentation and Community
- Visit our Documentation for detailed information on how to use CodeRabbit.
- Join our Discord Community to get help, request features, and share feedback.
- Follow us on X/Twitter for updates and announcements.
This was intentional because it feels like a more expected behavior to me. In general I think mapping undefined -> null is a more reasonable default behavior than just ignoring it. I'm open to being convinced otherwise. I'd also be happy supporting this change behind an optional param. Curious to hear others chime in here.
This was intentional because it feels like a more expected behavior to me. In general I think mapping
undefined->nullis a more reasonable default behavior than just ignoring it. I'm open to being convinced otherwise. I'd also be happy supporting this change behind anoptionalparam. Curious to hear others chime in here.
While it's probably working most of the time, defining a property with null is technically still defined. The properties describe what type to expect, and dealing with null and undefined used to be tedious in JS environments. The produced JSON Schema becomes also harder to read, and if you e.g. rely on form generators (like I do), then you need to add special logic to handle these unnecessary cases :/
For this reason, I've also opened a PR (https://github.com/colinhacks/zod/pull/4124) which treats all "to be undefined" types (optional, nullable and nonoptional) the same, merging with inner and rely on required property + simplifying additionalProperties for strict objects/interfaces.
My users typically have OpenAPI spec generated from Zod types to represent how to call the API. They will then instead use the Zod Types to actually parse the request.
If the JSON Schema was suggesting that null could be accepted but the Zod Type wouldn't accept it I think users would get frustrated. I think that given we have .nullable() and .nullish() which actually accept null we should keep that null behaviour behind those modifiers?
I prefer the behavior presented by samchungy. I am concerned that with the current behavior, the value according to the json schema and the result of the zod parsing are misaligned. (4.0.0-beta.20250412T085909)
import * as z from 'zod';
const schema = z.object({
value: z.string().optional(),
});
console.dir(z.toJSONSchema(schema), { depth: null });
// OUTPUT:
// {
// type: 'object',
// properties: {
// value: { oneOf: [ { type: 'string' }, { type: 'null' } ] }
// },
// required: []
// }
console.log(schema.safeParse({ value: null }).success);
// OUTPUT: false
console.dir(z.toJSONSchema(schema.shape.value), { depth: null });
// OUTPUT: { oneOf: [ { type: 'string' }, { type: 'null' } ] }
console.log(schema.shape.value.safeParse({ value: null }).success);
// OUTPUT: false
Here's the scenario I'm scared about:
- Pass an instruction to a LLM (for structured outputs etc) via JSON schema, telling it it can return
null. - The LLM returns
null - The zod parsing fails because the LLM returned
null
Is this a danger?
Either way, confusing null and undefined is never a good plan.
Hey 👋
Agree with OP, explicit and 1:1 > convenient.
I'd intuitively expect key optional to remove the prop name from required props list of the object type.
I'd expect nullable() to have the current behavior - oneOf with null.
I'd expect nullish() to be a combination of both.
I'd expect value optional to behave similarly to key optional as I'd expect it to be omitted when serialized.
Gotta agree with @samchungy.
{"oneOf": [{ type: "string" }, { "type": "null" }] } allows string | null, however z.string().optional() will fail on null [0], that's an issue by itself, because JSON Schema and Zod Schema won't have 1:1 behaviour anymore. And as Matt mentioned, mix-matching null and undefined ain't good (I personally consider that borderline grey area). At the end of day, it would end up causing unexpected behaviour, bugs, and overall bad DX.
Also, let's not forget:
undefined-> variable is nor defined, nor exists.null-> variable is defined but it holds no value (ornullvalue, but that's a technicality)
[0] Playground link
Here's the scenario I'm scared about:
- Pass an instruction to a LLM (for structured outputs etc) via JSON schema, telling it it can return
null.- The LLM returns
null- The zod parsing fails because the LLM returned
nullIs this a danger?
Either way, confusing
nullandundefinedis never a good plan.
A part from the theory here (which I agree with), a practical issue in todays LLM world is that many models only support a partial JSONSchema spec. I have had many, many issues trying to generate structured outputs using a union type using oneOf.
Obviously this may change in the future with better models but I think making null the default behavior here would cause serious headaches trying to adopt v4 into ai workflows
Merged in @zod/[email protected] and latest betas.