我有一个既可调用又可扩展的 javascript 函数/类。假设它名为Hello。
Hello 可以通过以下两种方式之一使用:
class Hi extends Hello { }
或者
Hello('there');
我将如何编写类型Hello以便 TypeScript 知道它既可调用又可扩展?
这样做的方法是声明Hello一个变量,它的类型是一个具有可调用和构造函数签名的接口:
// this is the type for an object that new Hello() creates
declare interface Hello {
foo(a: string): void;
}
// this is the type for Hello variable
declare interface HelloType {
(text: string): void;
new (...args: any[]): Hello;
}
declare var Hello: HelloType;
// can be used as a class
class Hi extends Hello {
bar(b: string): void {
this.foo(b);
}
}
// and as a function
Hello('there');
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3361 次 |
| 最近记录: |