typescript 对象的Zod返回类型,keysof()未类型化

icnyk63a  于 2023-02-25  发布在  TypeScript
关注(0)|答案(1)|浏览(176)

我尝试创建一个函数,它接受一个zod对象,并通过keyof()函数返回一个zod枚举。
我现在拥有的是:

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);
}

将鼠标悬停在tconst t: z.ZodEnum<["username", "password", "rememberMe", "redirectTo"]>上时,codesandbox上的highliter显示以下内容这将返回枚举,但TypeScript会引发错误Type 'ZodEnum<never>' is not assignable to type 'ReturnType<T["keyof"]>'.
我一直在试着向前看,但有些事情对我来说不对劲,我不知道我错在哪里。

cnjp1d6j

cnjp1d6j1#

我曾经尝试过ThePerplexedOne提供的一个答案,我发现如果我这样做,它会正确地推断。
因为在他们的例子中,你似乎不能将常量转换成联合体。这段代码正确地推断了类型键,也返回了一个枚举。

function getEnumFromSchema<S extends z.ZodRawShape>(schema: z.ZodObject<S>) {
  return schema.keyof();
}

function test() {
  const t = getEnumFromSchema(FormSchema);
  // t is inferred to be of type `z.ZodEnum<"username" | "password" | "rememberMe" | "redirectTo">`
}

相关问题