【发布时间】:2021-09-25 20:11:43
【问题描述】:
我喜欢 Zod 解析器,但我可能在创建表单库时不知所措。
在理想的最终状态下,输入形状被转换为创建{ fieldA: { value, onChange, errors } }。它适用于单个级别,但不清楚如何支持数组和嵌套对象。
typescript 可以像这样转换递归泛型吗?
Zod 表示这样的解析器:
const schema = z
.object({
name: z.string().min(3, 'Too short.'),
nested: z.object({
name: z.string(),
}),
repeat: z.array(z.object({
arrNest: z.string(),
})),
}).transform((v) => v.name);
然后使用类型推断:
const example = <Input extends { [v: string]: any }, Output extends unknown>(
schema: z.ZodType<Output, any, Input>
) => {
type Fields = {
[P in keyof Input]: {
value: Input[P];
};
};
return ({} as unknown) as Fields;
};
export const typed = example(schema);
名称具有所需的类型{ value: string },但重复具有:
相反,我想用对象和数组递归地应用它
然后types.repeat 将具有类型{ arrNest: { value: string } }[]
注意事项
zod object type 相当复杂..
但我只关心Input,表示为
export type ZodRawShape = { [k: string]: ZodTypeAny };
欢迎任何关于可行性或方向的想法!
【问题讨论】:
-
我对你的
example函数有点困惑,你为什么不能直接使用type MySchema = z.infer<typeof schema>? -
我正在编写一个可以重用的函数,也许
z.infer在这里更好,但我仍然需要更改所有原语的类型。例如,我将object({ fieldA: number })转换为{ fieldA: { value: number, onChange: (a: number) => void, errors } }我想自动生成输入道具。 -
您能否进一步解释一下您希望如何将类型更改为
fieldA: { value...?我不明白它是如何工作的,所以你想最终得到一个具有name、nested、repeat属性的对象?他们每个人都应该是一个带有{ value, onChange, errors }但输入正确的对象? -
我实际上已经这样做了。下一个级别是拥有
nested.name = { value, onChange, errors }。此外,这是关于获取编译器推断的类型。我知道如何在 javascript 中完成此操作。
标签: typescript typescript-generics zod