一个方法返回一个类类型:Widget
。
我想用下面的代码创建一个这种类型的对象:
const wType = def.getWidgetType(); // returns Widget as type
const obj = new wType('foo'); // use the const like a normal type with parameters
getWidgetType()
public getWidgetType(): any {
return TextWidget;
}
错误
错误 TS2351:无法将“new”与类型缺少调用或构造签名的表达式一起使用。
是否有一个“不错”的版本(没有 eval)来创建具有给定类类型的对象?
最佳答案
假设 getWidgetType
返回的是一个构造函数,您可以调用 new wType('foo')
提供 getWidgetType
的签名明确说明它返回构造函数签名。
例如,这段代码是有效的:
class Definition<T> {
// Takes in a constructor
constructor(public ctor: new (p: string) => T) {
}
// returns a constructor (aka a function that can be used with the new operator)
// return type annotation could be inferred here, was added for demonstrative purposes
getWidgetType() : new (p: string) => T{
return this.ctor;
}
}
const def = new Definition(class {
constructor(p: string) {}
});
const wType = def.getWidgetType();
const obj = new wType('foo')
关于javascript - typescript 创建来自变量的类型的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50693411/