Skip to content
New issue

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

Using .default with z.object doesn't do anything, and neither does .required if z.object has defaults #3482

Open
gotofritz opened this issue May 10, 2024 · 0 comments

Comments

@gotofritz
Copy link

gotofritz commented May 10, 2024

Hi, thanks for the great library.

I am to have two version of a schema, one with the fields optional and default values, the other with all fields required.

If I start from the optional version...

var allOptionals = z.object({
  hero: z.string().default("rick"),
  sidekick: z.string().default("morty"),
})
var allRequired = allOptionals.required();

allRequired.parse({});
// expected: error
// actual: { hero: "rick", sidekick: "morty" }

and if I start from the required version

var allRequired = z.object({
  hero: z.string(),
  sidekick: z.string(),
})
var allOptionals = allRequired.default({
  hero: "rick",
  sidekick: "morty",
});

allOptionals.parse({});
// expected: { hero: "rick", sidekick: "morty" }
// actual: error

How can I add a bunch of defaults to a z.object in one go, without definiing them individually? (I get them from an api call)

EDIT: I am aware of .transform and .refine, but they return a ZodEffect and not a ZodObject. I also need to use those schemas in .merge. I could use sourceType or innerType but it still doesn't come our right.

Thanks

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

1 participant