type DefaultType = {.....};
class A<MyInferedType> {
constructor(
private readonly paramFunc: (response: MyInferedType) => any,
private readonly optionalParamFunc?: () => Promise<MyInferedType>
) {}
async doSomething() {
// note the else branch! if optionalParamFunc is not defined i want to use a DefaultType value
const result = this.optionalParamFunc ? this.optionalParamFunc() : {} as DefaultType ;
this.paramFunc(result);
}
}
我想MyInferedType
从optionalParamFunc
if推断给构造函数。如果没有通过,我希望它能通过DefaultType
。我在玩infer关键字,但没有成功。我猜有些专家可以向我解释什么是正确的方法。
我应该可以如下使用它:
const defVal: DefaultType = {...};
const inferedVal: AnyTypeOfChoice = {...};
const a = new A((defVal) => {...});
const a2 = new A((inferedVal) => {...}, async () => inferedVal);
您实际上并不需要条件类型(即infer
关键字)的推断行为。一个简单的参数类型default似乎可以完成这项工作:
type DefaultType = { d: string };
class A<MyInferedType = DefaultType> {
constructor(
private readonly paramFunc: (response: MyInferedType) => any,
private readonly optionalParamFunc?: () => Promise<MyInferedType>
) {}
}
type AnyTypeOfChoice = {a: string }
const defVal: DefaultType = { d: ""};
const inferedVal: AnyTypeOfChoice = { a: ""};
const a = new A((defVal) => { defVal.d });
const a2 = new A((inferedVal) => { inferedVal.a }, async () => inferedVal);
关于实例化通用类型参数的值的问题,这是TS原则上不允许的。从类型的角度来看,checkthis.optionalParamFunc
和type参数之间没有关系MyInferedType
,因此就ts而言,您无法实例化任何对象,MyInferedType
因为您实际上不知道它的外观。
您可以使用类型断言来解决此问题:
const result = this.optionalParamFunc ? await this.optionalParamFunc() : {d: "asdsad"} as any as MyInferedType;
请注意,我们可以设想实际上具有this.optionalParamFunc
未定义的实例,而没有type参数DefaultType
。(new A<AnyTypeOfChoice>((inferedVal) => { inferedVal.a })
)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句