0

How can I declare something like that:

private componentsArr: <T extends Component>[];

So i can push objects that extends Component class to componentsArr

Edit: I have another problem

Here are screenshot:

Generic type problem

Problem description

What im doing worng?

4

1 回答 1

1

You need to specify the type constraint at the point where you declare T. If T is a class type parameter you can write it like this. For the method you need to constrain the parameter type to be derived from T not directly from Component because the compiler need to know that the argument type can be assigned to T in order to add it to the array:

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; 
    }
}
于 2017-10-31T10:42:14.413 回答