以下代码的TypeScript定义是什么?
function MyClass (arg) {
if (!(this instanceof MyClass)) {
return new MyClass(arg);
}
//...
}
我需要定义以支持同时调用new MyClass('Name')
和MyClass('Name')
。
答案 0 :(得分:1)
如果要为JavaScript中定义的函数编写TypeScript声明文件,则应编写:
declare const MyClass: {
(arg: /*arg type here*/): MyClass;
new (arg: /*arg type here*/): MyClass;
};
如果要在TypeScript中定义函数,则应编写:
const MyClass2 = <{
(arg: number): MyClass;
new (arg: number): MyClass;
}> function (arg) {
/* definition */
};
无论哪种方式,您都需要一个单独的interface MyClass
声明来声明实例类型。