问题
The following code will create a factory function in ES5:
function MyClass(val) {
if (!(this instanceof MyClass)) {
return new MyClass(val);
}
this.val = val;
}
This function can be called with or without the new
keyword:
var a = new MyClass(5);
var b = MyClass(5);
This works fine in Typescript, however I can't figure out how to create a declares file with merging that describes both behaviors. Is there a way to do this?
回答1:
interface MyClass {
val: {};
}
interface MyClassConstructor {
(val: {}): MyClass;
new (val: {}): MyClass;
}
declare const MyClass: MyClassConstructor;
来源:https://stackoverflow.com/questions/42095085/factory-function-in-a-typescript-declares-file-with-and-without-the-new-keyword