Skip to content
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

Unions in intersections still generate with "additionalProperties": false #68

Open
rijenkii opened this issue May 25, 2023 · 2 comments
Labels

Comments

@rijenkii
Copy link

See also: #64, #65.

Reproduction:

const left = z.union([
  z.object({ field1: z.number() }),
  z.object({ field3: z.string() }),
]);
const right = z.object({ field2: z.boolean() });
const intersection = z.intersection(left, right);
const schema = zodToJsonSchema(intersection);

Generates the following schema:

{
  "allOf": [
    {
      "anyOf": [
        {
          "type": "object",
          "properties": { "field1": { "type": "number" } },
          "required": ["field1"],
          "additionalProperties": false
        },
        {
          "type": "object",
          "properties": { "field3": { "type": "string" } },
          "required": ["field3"],
          "additionalProperties": false
        }
      ]
    },
    {
      "type": "object",
      "properties": { "field2": { "type": "boolean" } },
      "required": ["field2"]
    }
  ],
  "$schema": "http://json-schema.org/draft-07/schema#"
}

Because of "additionalProperties": false, no object can be successfully validated against this schema:
https://www.jsonschemavalidator.net/s/ddO3vtM2

Compared to schema with removed additionalProperties:
https://www.jsonschemavalidator.net/s/UO8HV6Lz

@ilyabo
Copy link

ilyabo commented Aug 17, 2023

We are experiencing the same issue. Is there a known workaround?

@rijenkii
Copy link
Author

Currently I'm just removing additionalProperties: false from generated schemas:

function deepRemoveKeys(obj, exclude) {
  if (obj instanceof Array) {
    return obj.map((i) => deepRemoveKeys(i, exclude));
  }
  if (typeof obj === "object") {
    return Object.fromEntries(
      Object.entries(obj)
        .filter(
          ([k, v]) => !(k in exclude && (exclude[k] === undefined || exclude[k] === v))
        )
        .map(([k, v]) => [k, deepRemoveKeys(v, exclude)])
    );
  }
  return obj;
}

const schema = deepRemoveKeys(zodToJsonSchema(obj), { additionalProperties: false });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants