zod icon indicating copy to clipboard operation
zod copied to clipboard

Strict + Intersection fails during parsing

Open jsamr opened this issue 5 months ago • 0 comments

Minimal reproduction (CodeSandbox):

import { z } from "zod";

const schema1 = z.object({
  foo: z.literal("foo"),
});

const schema2 = z
  .object({
    bar: z.literal("bar"),
  })
  .strict()
  .and(schema1);

const result = schema2.safeParse({
  foo: "foo",
  bar: "bar",
});

console.info(result.error);

Will display the following

ZodError: [
  {
    "code": "unrecognized_keys",
    "keys": [
      "foo"
    ],
    "path": [],
    "message": "Unrecognized key(s) in object: 'foo'"
  }
]

I'm unsure what is the desired behavior from a design perspective, but this behavior is misleading for sure: I would find either of these alternative behaviors more satisfactory (in the sense of not defying user's expectations):

  1. The "strictness" would propagate to the entire intersection;
  2. Zod would throw a runtime error when creating an "invalid" schema.

jsamr avatar May 19 '25 11:05 jsamr