Skip to content
Discussion options

You must be logged in to vote

I ended up using this (Zod V3):

function defaultButRequired<T extends z.ZodTypeAny>(schema: T, defaultValue: z.output<T>) {
    return schema.optional().default(defaultValue) as unknown as T;
}

const schema = z.object({
    name: defaultButRequired(z.string(), "default"),
});

type Input = z.input<typeof schema>; // { name: string }
type Output = z.output<typeof schema>; // { name: string }

const data = schema.parse({}); // { name: "default" }

Replies: 2 comments 1 reply

Comment options

You must be logged in to vote
1 reply
@BrendanC23
Comment options

Comment options

You must be logged in to vote
0 replies
Answer selected by BrendanC23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants