Typescript 具有静态工厂的抽象父级的子类的类型

Typescript 具有静态工厂的抽象父级的子类的类型,typescript,Typescript,我想引用一个类的类型,它扩展了一个抽象类,并且有一个在抽象父类中实现的静态工厂函数 我在这里学习了如何在抽象类中编写静态工厂: 请考虑此代码: abstract class Parent { public static factory<T extends Parent>(this: new (...args: any[]) => T) { return new this(); } } class Child1 extends Parent {

我想引用一个类的类型,它扩展了一个抽象类,并且有一个在抽象父类中实现的静态工厂函数

我在这里学习了如何在抽象类中编写静态工厂:

请考虑此代码:

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();

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


那么如何声明此类型呢?

在这种情况下,让typescript推断类型并使用
作为常量将是最简单的:

对于泛型类型,我们需要去掉
抽象构造函数
-类型,并将其更改为普通类型,以便能够通过
new this()
()实例化:

type TParent = typeof Parent;

...

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

...

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

let child1 = arr[0].factory(); // type Child1
let child2 = arr[1].factory(); // type Child2
// 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