首页 > 解决方案 > 具有静态工厂的抽象父类的子类的类型

问题描述

我想引用扩展抽象类并具有在其抽象父级中实现的静态工厂函数的类的类型。

我在这里学习了如何在抽象类中编写静态工厂: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();

我使用anyarr.

我想使用特定类型。

我试图这样声明它:

type TParent = typeof Parent;

...

const arr: TParent[] = [ Child1, Child2 ];

...

// i get an error for this line:
let child1 = arr[0].factory();

我收到错误“无法将抽象构造函数类型分配给非抽象构造函数类型”。

那么如何声明这个类型呢?

标签: typescript

解决方案


在这种情况下,让打字稿推断类型和使用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

推荐阅读