Zod default without making input type optional #3770
Answered
by
BrendanC23
BrendanC23
asked this question in
Q&A
-
I'm looking for a way to have a default value while keeping the input type unchanged. I want the default value to take effect when const schemaWithDefault = z.object({
a: z.string(),
b: z.string().default(""),
});
// I want { a: string; b: string; }, not { a: string; b?: string | undefined; }
type SchemaWithDefaultType = z.input<typeof schemaWithDefault>;
const data: unknown = { a: "a" };
const parsedData = schemaWithDefault.parse(data); // .default() works, b is set to "" as expected
const ExplicitlyDefinedType: SchemaWithDefaultType = {
a: z.string(),
// I want a TypeScript error because b is not defined
}; I've also looked at const schemaWithDefault = z.object({
a: z.string(),
b: z.string().catch(""),
});
// I want { a: string; b: string; }, not { a: string; b: unknown; }
type SchemaWithDefaultType = z.input<typeof schemaWithDefault>; Is there a way to accomplish this? |
Beta Was this translation helpful? Give feedback.
Answered by
BrendanC23
Sep 3, 2025
Replies: 2 comments 1 reply
-
@BrendanC23 Did you find a solution? |
Beta Was this translation helpful? Give feedback.
1 reply
-
I ended up using this (Zod V3):
|
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
BrendanC23
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I ended up using this (Zod V3):