我有这个界面I
:
import { z } from "zod";
const schema = z.object({
name: z.string(),
});
type S = z.infer<typeof schema>;
interface I {
process: (obj: S) => object;
schema: z.ZodSchema;
}
它包含一个 Zod 模式和一个处理验证结果的函数。 (假设我有充分的理由不在 process
函数中进行验证。)
我想将其转换为一个基于 Zod 模式的接口(interface),确保 schema
包含所述模式,并且 process
接受一个 obj
在模式 TypeScript 类型的参数中。
最佳答案
z.ZodSchema
是一个通用类,您可以在其中定义所需架构的类型。
基本上,您应该将界面重构为以下内容:
interface I<T> {
process: (obj: T) => object;
schema: z.ZodSchema<T>;
}
现在,I.schema
接受具有给定类型的 z.ZodSchema
,与使用 I.process
函数相同。
检查here
关于typescript - 基于 Zod 模式将接口(interface)通用化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74718183/