Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract constructor type in TypeScript

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.

like image 371
John Weisz Avatar asked Apr 27 '16 09:04

John Weisz


People also ask

Can abstract class have constructor TypeScript?

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.

What is the type for a constructor in TypeScript?

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.

Are there abstract classes in TypeScript?

TypeScript has the ability to define classes as abstract. This means they cannot be instantiated directly; only nonabstract subclasses can be.

What are abstract methods TypeScript?

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.


1 Answers

Was just struggling with a similar problem myself, and this seems to work for me:

type Constructor<T> = Function & { prototype: T } 
like image 108
Tehau Cave Avatar answered Oct 03 '22 13:10

Tehau Cave