colinhacks / zod

TypeScript-first schema validation with static type inference
https://zod.dev
MIT License
33.09k stars 1.15k forks source link

Valid union-of-partials data does not parse even though it conforms to one (or more) of the union members #3584

Open brenfwd opened 3 months ago

brenfwd commented 3 months ago

Consider this example:

import { z } from "zod";

const FooASchema = z.object({
  type: z.literal("A"),
  a: z.number(),
});

const FooBSchema = z.object({
  type: z.literal("B"),
  b: z.number(),
});

// const FooSchema = z.union([FooASchema, FooBSchema]);
const PartialFooSchema = z.union([FooASchema.partial(), FooBSchema.partial()]);

const input: unknown = { b: 12 };

const typed = PartialFooSchema.safeParse(input);

console.log("Input:", input);
console.log("Error:", typed.error);
console.log("Data:", typed.data);

Here I would expect that typed.data would be { b: 12 } since input should validate against FooBSchema.partial(). However, the actual behavior is (1) no error; and (2) typed.data is {}.

brenfwd commented 3 months ago

BossHogg97 commented 1 month ago

Hi, i have the same issue. Is there any solution? Thanks :)