How to make a generic getter like z.infer<> in Typescript

问题描述 投票:0回答:2

我已经学习 Typescript 几个月了,最近我开始发现 zod,我想知道如何构建这样一个实用的 getter,例如

z.infer<>
z.input<>
甚至
z.output<>

我的理解是

z
是一个类,它有一个 getter“方法”,它采用泛型并返回一个类型,但我不知道它是如何工作的

我试图复制它但无法弄清楚,有人可以帮忙吗?

typescript typescript-generics getter zod
2个回答
1
投票

如果我们有一些具有通用类型的类并使用它:

class Validator<T> { validate(value: any): value is T { /* implementation does not matter */ return true; } }

然后我们可以使用

infer
提取泛型:

type Infer<V> = V extends Validator<infer T> ? T : never;

你可以像这样使用它:

const validator = new Validator<string>();

type S = Infer<typeof validator>; // string

这是Zod的

z.Infer
的基础。

游乐场


0
投票

根据我对源代码的快速挖掘,这些类型似乎定义在

helpers/types.ts

export type TypeOf<T extends ZodType<any, any, any>> = T["_output"];
export type input<T extends ZodType<any, any, any>> = T["_input"];
export type output<T extends ZodType<any, any, any>> = T["_output"];
export type { TypeOf as infer };
// ...
export abstract class ZodType<
  Output = any,
  Def extends ZodTypeDef = ZodTypeDef,
  Input = Output
> {
  readonly _type!: Output;
  readonly _output!: Output;
  readonly _input!: Input;
  readonly _def!: Def;
// ...

这就是您构建它们的方式。

© www.soinside.com 2019 - 2024. All rights reserved.