zod icon indicating copy to clipboard operation
zod copied to clipboard

intersection of records differs from typescript

Open bug-brain opened this issue 2 years ago • 4 comments

const type = z.intersection(
  z.object({ a: z.null() }),
  z.record(z.string().refine((s): s is "b" => s === "b"), z.undefined()),
)
const input: z.infer<typeof type> = { a: null, b: undefined }
type.parse(input)

should work according to the types but throws

ZodError: [
  {
    "code": "custom",
    "message": "Invalid input",
    "path": [
      "a"
    ]
  },
  {
    "code": "invalid_type",
    "expected": "undefined",
    "received": "null",
    "path": [
      "a"
    ],
    "message": "Expected undefined, received null"
  }
]

A key is not required to match the index signature but if it does its value should match the intersection of value types.

bug-brain avatar Oct 07 '22 15:10 bug-brain

Confirmed that this is broken, and I agree that we should match TypeScript's behavior here. PRs welcome!

scotttrinh avatar Oct 07 '22 17:10 scotttrinh

Hey! I can do this. Is the desired behaviour that key/value pairs are stripped off from the object if the key parsing is not valid?

ochan12 avatar Oct 23 '22 13:10 ochan12

Yep I agree, though some people will be annoyed - the same set that are annoyed that z.object also strips unknown keys by default. We'll need to add .strict and .passthrough to ZodRecord as well so there's still a way to opt into the old behavior.

colinhacks avatar Nov 17 '22 21:11 colinhacks

@colinhacks I created a PR without the strict and the passthrough #1514 . Will it be necessary to add it?

ochan12 avatar Nov 17 '22 22:11 ochan12

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

stale[bot] avatar Feb 15 '23 23:02 stale[bot]

@colinhacks I believe this issue has been prematurely closed. The PR was also auto-closed without any feedback. Is this being addressed in a different issue?

chuck-flowers avatar Jun 22 '23 18:06 chuck-flowers