javascript - typescript 创建来自变量的类型的对象

标签 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;
}

错误

错误 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/

相关文章:

typescript - Javascript : Function equivalent of `for (let p in this)`

javascript - 如何在 Angular 2+ 中使用第三方 js 库而不安装类型?

javascript - 更改文本字段边框颜色并验证电子邮件的@

angular - Material 2 : Show/Hide md-sidenav depending on media

javascript - 如何使用当前的 Form API 将父组件的 FormGroup 传递给其子组件

angular - 我如何替换 Angular ngx-charts 中图表的 "legend"单词?

typescript - 如何从 github :DefinitelyTypes using typings 安装 .d.ts 文件

javascript - 如何使用 react 钩子(Hook)将文件放入状态变量中

javascript - MVC 中的波斯日历,Asp.net

javascript - 等待带有回调的异步函数