Utility type to convert an abstract class to a non-abstract subclass?

20 Views Asked by At

I have an abstract class, and I would like to generate a type that matches any non-abstract subclass of that type, not its instance. Is this possible?

abstract class A {
}
function b(type: NonAbstractDescendant<typeof A>) {
}
1

There are 1 best solutions below

0
jilles On

My guess is that the function (b) needs type to create instances. This suggests a type like { new() : A } (with the appropriate parameter types), or if static properties and/or methods are required { new(): A } & typeof A. In either case, this only matches subclasses of which the constructors take compatible parameters.

It is possible to avoid repeating the constructor parameters like { new(...args: ConstructorParameters<typeof B>): B } & typeof B but it is well possible that this is longer than simply repeating them.

An example:

abstract class A {}
class D extends A {}
function f(cons: { new() : A } & typeof A): A {
    return new cons();
}
f(D);