Skip to content
This repository was archived by the owner on Jan 5, 2026. It is now read-only.
This repository was archived by the owner on Jan 5, 2026. It is now read-only.

Collapse supersets in unions/arrays by default #401

@EllAchE

Description

@EllAchE

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!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions