I'm wanting to do something like this:
class Base {
static foo(): <???>; // <= What goes here?
}
class Subclass extends Base {}
Subclass.foo() // <= I want this to have a return type of Subclass, not Base
TypeScript has been adding features aggressively over the past year, including support for using class types in generics. This example compiles in 2.3 or later:
interface Constructor<M> {
new (...args: any[]): M
}
class Base {
static foo<T extends Base>(this: Constructor<T>): T {
return new this()
}
}
class Subclass extends Base {
readonly bar = 1
}
// Prove we have a Subclass instance by invoking a subclass-specific method:
Subclass.foo().bar
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