Factory function in a Typescript declares file, with and without the new keyword

余生颓废 提交于 2020-01-02 02:28:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!