Currently, I'm in the process of developing a function that takes a zod object as input and produces a zod enum using the keyof()
function.
This is what I have so far:
const FormSchema = z.object({
username: z.string().trim().min(1).max(20),
password: z.string().trim().min(12).max(100),
rememberMe: z.coerce.boolean().optional().default(false),
redirectTo: z.string().trim().startsWith("/"),
});
type Schema<T extends z.AnyZodObject> = z.infer<T>
type SchemaEnum<T extends z.AnyZodObject> = ReturnType<T["keyof"]>;
function getEnumFromSchema<T extends z.AnyZodObject> (schema: T): SchemaEnum<T> {
const shape = schema._type;
return shape.keyof();
}
function test () {
const t = getEnumFromSchema(FormSchema);
}
On codesandbox, when I hover over t
, it displays
const t: z.ZodEnum<["username", "password", "rememberMe", "redirectTo"]>
Although this returns an enum, TypeScript throws the error Type 'ZodEnum<never>' is not assignable to type 'ReturnType<T["keyof"]>'.
I've been trying to troubleshoot this issue, but something feels off to me, and I haven't been able to pinpoint where I might be going wrong.