相关疑难解决方法(0)

在没有new的情况下调用TypeScript类上的构造函数

在JavaScript中,我可以定义一个构造函数,可以使用或不使用调用new:

function MyClass(val) {
    if (!(this instanceof MyClass)) {
        return new MyClass(val);
    }

    this.val = val;
}
Run Code Online (Sandbox Code Playgroud)

然后我可以MyClass使用以下任一语句构造对象:

var a = new MyClass(5);
var b = MyClass(5);
Run Code Online (Sandbox Code Playgroud)

我尝试使用下面的TypeScript类获得类似的结果:

class MyClass {
    val: number;

    constructor(val: number) {
        if (!(this instanceof MyClass)) {
            return new MyClass(val);
        }

        this.val = val;
    }
}
Run Code Online (Sandbox Code Playgroud)

但是打电话MyClass(5)给了我错误Value of type 'typeof MyClass' is not callable. Did you mean to include 'new'?

有什么办法可以让这个模式在TypeScript中运行吗?

constructor typescript

21
推荐指数
2
解决办法
1万
查看次数

标签 统计

constructor ×1

typescript ×1