这是indexloc提供的服务,不要输入任何密码
Skip to content

Add .strict() mode for Zod union schemas to prevent data loss from partial matches #2504

@Joshua-hypt

Description

@Joshua-hypt

Description

Problem

When generating Zod schemas for OpenAPI specs with union/oneOf types, the current implementation creates unions that can cause unexpected data loss. Zod's default union behavior returns the first successfully matching schema, which means less specific schemas can "steal" matches from more specific ones, silently dropping valid properties.

Example

Given these generated schemas:

typescriptconst schema = z.union([
    z.object({ value: z.number() }),                    // Schema A
    z.object({ value: z.number(), value2: z.number() }) // Schema B
]);

const data = { value: 5, value2: 10 };
const result = schema.parse(data); // Returns: { value: 5 } - value2 is lost!

Schema A matches first and returns incomplete data, even though Schema B would be a complete match.

Proposed Solution

Add a configuration option to generate Zod schemas with .strict() mode for union members, which would reject objects with extra properties:

const schema = z.union([
    z.object({ value: z.number() }).strict(),
    z.object({ value: z.number(), value2: z.number() }).strict()
]);

const data = { value: 5, value2: 10 };
const result = schema.parse(data); // Now correctly returns: { value: 5, value2: 10 }

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions