在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中运行吗?