TypeScript 中的抽象构造函数类型 [英] Abstract constructor type in TypeScript
问题描述
TypeScript 中非抽象类(非抽象构造函数)的类型签名如下:
声明类型 ConstructorFunction = new (...args: any[]) =>任何;
这也称为 newable 类型.但是,我需要一个 abstract 类(抽象构造函数)的类型签名.我知道它可以被定义为具有 Function
类型,但这方式太宽泛了.没有更精确的替代方法吗?
为了澄清我的意思,以下小片段演示了抽象构造函数和非抽象构造函数之间的区别:
声明类型 ConstructorFunction = new (...args: any[]) =>任何;抽象类实用程序{...}var UtilityClass: ConstructorFunction = Utilities;//错误.
<块引用>
类型typeof Utilities"不可分配给类型new (...args: any[]) => any".
<块引用>不能将抽象构造函数类型分配给非抽象构造函数类型.
我自己也遇到了类似的问题,这似乎对我有用:
类型构造函数= 功能 &{原型:T}
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.
Was just struggling with a similar problem myself, and this seems to work for me:
type Constructor<T> = Function & { prototype: T }
这篇关于TypeScript 中的抽象构造函数类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!