I have 2 enums, const Option1 = z.enum(["option1"])
and const Option2 = z.enum(["option2"])
.
I want to merge these two into z.ZodEnum<["option1", "option2"]>
The only way I came up with so far is
export const Options = z.enum([
...Option1.options,
...Option2.options,
]);
// Options.options is now ["option1", "option2"]
Is there any zod native way to do this?
the issue you're facing here is due to the type of the combined options.
const allOptions = [...Option1.options, ...Option2.options]
the inferred type of allOptions
in this case is: ("option1" | "option2")[]
and zod can't create an enum out of that.
however, if you define allOptions
like this:
const allOptions = [...Option1.options, ...Option2.options] as const
then the inferred type of allOptions
will be the tuple ["option1", "option2"]
which is exactly what you want.
so, putting that all together, to combine the options, you'd say:
const Options = z.enum([...Option1.options, ...Option2.options] as const)
and the inferred type of Options will be z.ZodEnum<["option1", "option2"]>