I have a generic static method in an abstract class:
abstract class Base {
static find<T extends Base>(options?: Object): Promise<T[]> {
return findResults(options);
}
}
And I want to specify it's type in an derived class:
class Extended extends Base {
static find<Extended>(options?: Object): Promise<Extended[]>;
// Error: Function implementation is missing or not immediately following the declaration.
}
Is this behavior supported in any way by Typescript?
That type seems to violate the Liskov substitution principle for the static side of
Extended
. Apparently theExtended
constructor needs to be a validBase
constructor, so ifBase.find()
can return aPromise<T[]>
for anyT
that extendsBase
, thenExtended.find()
should be able to do that too.Generics in static methods are weird, since static members can't access the type parameters of the class. But maybe what you want isn't really generic at all... you want
Base.find()
to returnPromise<Base[]>
, andExtended.find()
to returnPromise<Extended[]>
, right? That sounds like a motivating example for polymorphicthis
. Unfortunately polymorphicthis
isn't supported for static members, at least as of yet.My suggestion would be to just manually implement the relationship you expect:
Note that all I've done there is declare that
Extended.find()
returns aPromise<Extended[]>
without changing its implementation fromBase.find()
. That might not be type safe, unless the implementation ofBase.find()
is smart enough to know how to do this. I kind of doubt it, so be careful. You may instead want to implement it differently:Okay, hope that helps. Good luck!