Typescript创建一个来自变量

时间:2018-06-05 06:26:33

标签: javascript angular typescript class oop

方法返回一个类类型: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;
}

错误

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

有没有"很好" version(没有eval)创建具有给定类类型的对象?

1 个答案:

答案 0 :(得分:4)

假设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')