【发布时间】:2016-08-21 12:43:46
【问题描述】:
TypeScript 中非抽象类(非抽象构造函数)的类型签名如下:
declare type ConstructorFunction = new (...args: any[]) => any;
这也称为 newable 类型。但是,我需要 abstract 类(抽象构造函数)的类型签名。我知道它可以被定义为具有Function 类型,但这方式 太宽泛了。没有更精确的替代方案吗?
编辑:
为了澄清我的意思,下面的小sn-p演示了抽象构造函数和非抽象构造函数之间的区别:
declare type ConstructorFunction = new (...args: any[]) => any;
abstract class Utilities {
...
}
var UtilityClass: ConstructorFunction = Utilities; // Error.
类型 'typeof Utilities' 不可分配给类型 'new (...args: any[]) => any'。
不能将抽象构造函数类型分配给非抽象构造函数类型。
【问题讨论】:
-
您能详细说明一下吗?也许提供更多代码?为什么在这种情况下抽象类和非抽象类之间存在差异? ctor 从不抽象。
-
@NitzanTomer 感谢您的帮助。我已将minimal reproducible example 编辑到问题中以演示问题。基本上,我需要传递一个类作为参数。
ConstructorFunction类型适用于非抽象类,但不适用于抽象类。
标签: constructor typescript abstract-class