我遇到了一个关于泛型函数中类型推断的TypeScrip问题.
以下是代码的简化版本:
type FnObj<I extends z.ZodType> = {
input: I,
func: (input: I extends z.ZodType<infer U> ? U : never) => void
}
type Objs<I extends z.ZodType = z.ZodType> = {
[key: string]: FnObj<I>
}
function createFormDef<FF extends Objs>(formObject: FF) {
return formObject;
}
createFormDef({
test: {
input: z.object({
d: z.number(),
}),
func: (input) => {
input.dsf // This line is not throwing an error, although it should be typed as {d: number}.
},
},
});
我已经try 移除Objs的泛型,以使单键成为其自己的类型.但这并没有奏效.如下所示:(还删除了Zod部分)
type FnObj<I extends any = any> = {
input: I,
func: (input: I) => void
}
type Objs = {
[key: string]: FnObj
}
function createFormDef(formObject: Objs) {
return formObject;
}
createFormDef({
test: {
input: {
hello: 10
},
func: (input) => {
input.dsf // still not working, should typed as {hello:number}
},
},
});