TypeScript:我如何编写可调用/可扩展实体的类型?

时间:2017-02-17 03:36:06

标签: typescript

我有一个可调用和可扩展的javascript函数/类。我们说它的名字是Hello

Hello可以通过以下两种方式之一使用:

class Hi extends Hello { }

Hello('there');

我如何编写Hello的类型,以便TypeScript知道它既可调用又可扩展?

1 个答案:

答案 0 :(得分:4)

执行此操作的方法是将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');