如何在打字稿中声明仅接受某些 class 扩展的通用 属性?

How to declare generic property that accept only extension of some class in typescript?

我怎样才能声明这样的东西:

private componentsArr: <T extends Component>[];

所以我可以将扩展 Component class 的对象推送到 componentsArr

编辑:我还有一个问题

截图如下:

我在做什么?

您需要在声明的地方指定类型约束 T。如果 T 是 class 类型的参数,你可以这样写。对于该方法,您需要将参数类型限制为从 T 派生,而不是直接从 Component 派生,因为编译器需要知道参数类型可以分配给 T 以便添加它到数组:

class MyClass<T extends Component> {
    private componentsArr: T[]
    addComponent<TSub extends T>(c: new () => TSub): TSub {
        const newComponent = new c(); 
        this._components.push(newComponent); 
        return newComponent; 
    }
}