Factory function in a Typescript declares file, wi

2019-04-24 07:17发布

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条回答
做个烂人
2楼-- · 2019-04-24 07:35
interface MyClass {
  val: {};     
}

interface MyClassConstructor {
  (val: {}): MyClass;
  new (val: {}): MyClass;
}

declare const MyClass: MyClassConstructor;
查看更多
登录 后发表回答