typescript - 具有静态工厂的抽象父类的子类的类型
问题描述
我想引用扩展抽象类并具有在其抽象父级中实现的静态工厂函数的类的类型。
我在这里学习了如何在抽象类中编写静态工厂:https ://stackoverflow.com/a/65717206/923846 。
请考虑以下代码:
abstract class Parent {
public static factory<T extends Parent>(this: new (...args: any[]) => T) {
return new this();
}
}
class Child1 extends Parent { }
class Child2 extends Parent { }
// what specific type can i use instead of "any" here:
const arr: any[] = [ Child1, Child2 ];
let child1 = arr[0].factory();
let child2 = arr[1].factory();
我使用any
了arr
.
我想使用特定类型。
我试图这样声明它:
type TParent = typeof Parent;
...
const arr: TParent[] = [ Child1, Child2 ];
...
// i get an error for this line:
let child1 = arr[0].factory();
我收到错误“无法将抽象构造函数类型分配给非抽象构造函数类型”。
那么如何声明这个类型呢?
解决方案
在这种情况下,让打字稿推断类型和使用as const
(游乐场)是最简单的:
const arr = [ Child1, Child2 ] as const;
let child1 = arr[0].factory(); // type Child1
let child2 = arr[1].factory(); // type Child2
对于泛型类型,我们需要去掉abstract constructor
-type 并将其更改为普通类型,以便能够通过new this()
(playground)实例化:
// convert the abstract constructor to a normal one and add the static functions via typeof Parent
type ParentSubClass = {new() : Parent} & (typeof Parent);
const arr: ParentSubClass[] = [ Child1, Child2 ];
let child1 = arr[0].factory(); // type Parent
let child2 = arr[1].factory(); // type Parent
推荐阅读
- node.js - pm2 节点服务器上 dns.js 上的 DNS 查询
- git - 如何避免在特定提交时启动自动管道?
- go - 为什么这个 websocket 服务器不向连接的客户端广播?
- python - 如何使用 Python 计算 csv 中唯一值的数量
- c# - 什么是 WebForm/WebBrowser 中的 NewWindow2 和 NewWindow3
- excel - 如何解决 VBA 上的错误
- tensorflow - 如何在 Tensorflow 2 中使用具有急切模式的可初始化迭代器为 ON
- javascript - 在 UL、LI 和标签内的 Bootstrap 下拉列表中获取选中复选框的 id,然后根据是否选中其他复选框
- css - 向页面添加多个 visualforce 组件时出现问题
- java - 使用 libGDX 以小 (<0.5) 比例渲染字体时出现问题