Joh*_*isz 26 constructor abstract-class typescript
TypeScript中非抽象类(非抽象构造函数)的类型签名如下:
declare type ConstructorFunction = new (...args: any[]) => any;
Run Code Online (Sandbox Code Playgroud)
这也称为新类型.但是,我需要一个抽象类的类型签名(抽象构造函数).我的理解是可以被定义为具有类型Function,但就是这样过于宽泛.难道没有更精确的替代方案吗?
编辑:
为了澄清我的意思,下面的小片段演示了抽象构造函数和非抽象构造函数之间的区别:
declare type ConstructorFunction = new (...args: any[]) => any;
abstract class Utilities {
...
}
var UtilityClass: ConstructorFunction = Utilities; // Error.
Run Code Online (Sandbox Code Playgroud)
类型'typeof Utilities'不能分配给'new(... args:any [])=> any'.
无法将抽象构造函数类型分配给非抽象构造函数类型.
Mat*_*ens 36
从 TypeScript 4.2 开始,您可以使用抽象构造函数类型:
abstract class Utilities {
abstract doSomething(): void;
}
type ConstructorFunction = abstract new (...args: any[]) => any;
var UtilityClass: ConstructorFunction = Utilities; // ok!
Run Code Online (Sandbox Code Playgroud)
小智 32
我自己只是在遇到类似的问题,这似乎对我有用:
type Constructor<T> = Function & { prototype: T }
Run Code Online (Sandbox Code Playgroud)