Typescript 创建来自变量的类型的对象

Wat*_*ont 4 javascript oop class typescript angular

方法返回一个类类型:Widget

我想用以下代码创建这种类型的对象:

const wType = def.getWidgetType(); // returns Widget as type
const obj = new wType('foo'); // use the const like a normal type with parameters
Run Code Online (Sandbox Code Playgroud)

getWidgetType()

public getWidgetType(): any {
 return TextWidget;
}
Run Code Online (Sandbox Code Playgroud)

错误

error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature.

是否有一个“好的”版本(没有 eval)来创建具有给定类类型的对象?

Tit*_*mir 5

假设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')
Run Code Online (Sandbox Code Playgroud)

  • 你的例子帮助我解决了我的问题。谢谢!在我的代码中,我只需将返回类型更改为 `getWidgetType(): new (id: string) =&gt; TextWidget` (2认同)