8000 v4: Error when extending object with record · Issue #4426 · colinhacks/zod · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

v4: Error when extending object with record #4426

New issue
8000

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
mfenn opened this issue May 19, 2025 · 3 comments
Closed

v4: Error when extending object with record #4426

mfenn opened this issue May 19, 2025 · 3 comments

Comments

@mfenn
Copy link
mfenn commented May 19, 2025

Node v22.14.0, Zod v3.25.3

In this example I have a schema constructed by extending an object with a record.

import { z } from "zod/v4";

const foo = z.object({ a: z.string() });
const bar = z.record(z.string(), z.any());
const baz = foo.extend(bar);
baz.safeParse({ a: "a", b: "b" });

I get this runtime error on the safeParse call.

TypeError: Cannot read properties of undefined (reading 'optin')
    at file://.../node_modules/zod/dist/esm/v4/core/util.js:253:30
    at Array.filter (<anonymous>)
    at Module.optionalKeys (file:/.../node_modules/zod/dist/esm/v4/core/util.js:252:31)
    at file://.../node_modules/zod/dist/esm/v4/core/schemas.js:687:28
    at get value (file://.../node_modules/zod/dist/esm/v4/core/util.js:34:31)
    at inst._zod.parse (file://.../node_modules/zod/dist/esm/v4/core/schemas.js:781:39)
    at Module.<anonymous> (file://.../node_modules/zod/dist/esm/v4/core/parse.js:33:32)
    at inst.safeParse (file://.../node_modules/zod/dist/esm/v4/classic/schemas.js:52:46)

May be related to #4338?

@colinhacks
Copy link
Owner

The .extend() method only accepts plain objects with additional fields, like so:

const foo = z.object({ a: z.string() });
const baz = foo.extend({ anotherField: z.string() });

It seems like what you're looking for is this:

const foo = z.object({ a: z.string() });
const baz = foo.catchall(z.any());

I'll work on improving the errors here.

@mfenn
Copy link
Author
mfenn commented May 19, 2025

In my real example I'm trying to extend an object with a record keyed by an enum. What is the correct way to do that?

Edit: I was able to switch my record to an object and then just spread its shape in order to merge/extend them.

@valerii15298
Copy link

@colinhacks would be nice to have error on .extend step instead of on safeParse step. Having an error as early as possible would be beneficial.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants
0