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

Collapse supersets in unions/arrays by default #401

Open
EllAchE opened this issue May 28, 2024 · 2 comments
Open

Collapse supersets in unions/arrays by default #401

EllAchE opened this issue May 28, 2024 · 2 comments

Comments

@EllAchE
Copy link

EllAchE commented May 28, 2024

Having nullable properties in a json array results in excessively large zod schemas.

I encountered this specifically when converting JSON to zod but it applies in other use cases as well, if it isn't solved for them. The expected behavior here is that array types should rarely (possibly never) result in union types. The actual behavior is that the schema is constructed as a union. I would suggest adding a flag for the current (union) behavior and returning recursively merged types by default.

Here's a trivial example. Imagine I have this JSON

[{"a": "b", "b":1}, {"a": "C", "c": 1}, {"b": 2, "c": 1}]

The resulting zod type is

import { z } from "zod"

export const schema = z.array(
  z.union([
    z.object({ a: z.string(), b: z.number() }),
    z.object({ a: z.string(), c: z.number() }),
    z.object({ b: z.number(), c: z.number() })
  ])
)

What I would write if doing this as a human:

export const schema = z.array(
    z.object({ a: z.string().optional(), b: z.number().optional(), c: z.number().optional }),
)

As you can imagine for non trivial cases where properties can be nullable/vary in types you can end up with excessively large union types.

I believe this problem has already been solved in some related libraries, such as https://jvilk.com/MakeTypes/. I'd love to see a similar implementation to recursively merge unions in arrays; I'd like to use this tool but this is limiation for me currently!

@EllAchE
Copy link
Author

EllAchE commented May 28, 2024

Traced the issue a little further and looks like this is just referencing the https://www.npmjs.com/package/json-schema-to-zod library. I'll leave the issue open as it still matters to have the UI but that's where the change will need to be made

UPDATE - decided to push a simple fix here

@EllAchE
Copy link
Author

EllAchE commented May 28, 2024

Went ahead and fixed this for myself, and will open a PR

UPDATE - PR at #402

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

No branches or pull requests

1 participant