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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With