本文介绍了在Typescript声明文件中的工厂函数,包含和不包含new关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码将在ES5中创建一个工厂函数:
The following code will create a factory function in ES5:
function MyClass(val) {
if (!(this instanceof MyClass)) {
return new MyClass(val);
}
this.val = val;
}
可以使用或不使用 new调用此函数
keyword:
This function can be called with or without the new
keyword:
var a = new MyClass(5);
var b = MyClass(5);
这在Typescript中工作正常,但我无法弄清楚如何用合并,描述了这两种行为。有没有办法做到这一点?
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?
推荐答案
interface MyClass {
val: {};
}
interface MyClassConstructor {
(val: {}): MyClass;
new (val: {}): MyClass;
}
declare const MyClass: MyClassConstructor;
这篇关于在Typescript声明文件中的工厂函数,包含和不包含new关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!