【问题标题】:Turn interface generic based on Zod schema基于 Zod schema 的转接口通用
【发布时间】:2022-12-16 15:30:00
【问题描述】:

我有这个接口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 模式的接口,确保 schema 包含所述模式,并且 process 在模式 TypeScript 类型的参数中采用 obj

【问题讨论】:

    标签: typescript typescript-typings typescript-generics zod


    【解决方案1】:

    z.ZodSchema 是一个通用类,您可以在其中定义所需模式的类型。

    基本上,您应该将界面重构为以下内容:

    interface I<T> {
      process: (obj: T) => object;
      schema: z.ZodSchema<T>;
    }
    

    现在I.schema 接受具有给定类型的z.ZodSchema,与使用I.process 函数相同。

    检查here

    【讨论】:

    • 谢谢!但也许你可以添加一个用法示例?我在如何使用它时遇到了一些问题。 Playground link
    • @KentLarsson 抱歉回复晚了,我已经更新了我的答案,如果您仍然遗漏了什么,请告诉我。
    猜你喜欢
    • 1970-01-01
    • 2011-01-17
    • 2022-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多