The type signature for a non-abstract class (non-abstract constructor function) in TypeScript is the following:
declare type ConstructorFunction = new (...args: any[]) => any;
This is also called a newable type. However, I need a type signature for an abstract class (abstract constructor function). I understand it can be defined as having the type Function
, but that is way too broad. Isn't there a more precise alternative?
Edit:
To clarify what I mean, the following little snippet demonstrates the difference between an abstract constructor and a non-abstract constructor:
declare type ConstructorFunction = new (...args: any[]) => any; abstract class Utilities { ... } var UtilityClass: ConstructorFunction = Utilities; // Error.
Type 'typeof Utilities' is not assignable to type 'new (...args: any[]) => any'.
Cannot assign an abstract constructor type to a non-abstract constructor type.
TypeScript has supported abstract classes since 2015, which provides compiler errors if you try to instantiate that class. TypeScript 4.2 adds support for declaring that the constructor function is abstract.
typeof Class is the type of the class constructor. It's preferable to the custom constructor type declaration because it processes static class members properly.
TypeScript has the ability to define classes as abstract. This means they cannot be instantiated directly; only nonabstract subclasses can be.
A TypeScript Abstract class is a class which may have some unimplemented methods. These methods are called abstract methods. We can't create an instance of an abstract class. But other classes can derived from abstract class and reuse the functionality of base class.
Was just struggling with a similar problem myself, and this seems to work for me:
type Constructor<T> = Function & { prototype: T }
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