简体   繁体   English

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

[英]Typescript create object of a type which comes from a variable

A method returns me a class type: Widget . 一个方法给我返回了一个类类型: Widget

I want to create a object of this type with the following code: 我想用以下代码创建这种类型的对象:

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

getWidgetType() getWidgetType()

public getWidgetType(): any {
 return TextWidget;
}

Error 错误

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

Is there a "nice" version (without eval) to create a object with a given class type? 是否有一个“不错的”版本(没有eval)来创建具有给定类类型的对象?

Assuming what getWidgetType returns is a constructor, you can invoke new wType('foo') provided the signature of getWidgetType explicitly states it returns a constructor signature. 假设getWidgetType返回的是构造函数,则可以调用new wType('foo')前提是getWidgetType的签名明确声明其返回构造函数签名。

For example this code would be valid: 例如,此代码将有效:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM