问题描述:

I have a javascript function/class that is both callable and extensible. Let's say it's named Hello.

Hello can be used in one of two ways:

class Hi extends Hello { }

or

Hello('there');

How would I write the typings for Hello so that TypeScript knows it's both callable and extensible?

网友答案:

The way to do it is to declare Hello as a variable having a type which is an interface with both callable and constructor signatures:

// 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');
相关阅读:
Top