gpt4 book ai didi

angular - 如何传递通用类型并在 Angular 2 组件中创建此类型的实例

转载 作者:行者123 更新时间:2023-12-02 09:12:20 25 4
gpt4 key购买 nike

我如何在 Angular 2/Typescript 中创建一个能够创建通用类型实例的通用组件?

@Component({
selector: 'generic',
template: 'generic.html'
})
export class GenericComponent<T> {
private array: T[];

addElement() {
const object = new T();
this.array.push(object);
}
}

目前我收到一条错误消息:

TS2693: 'T' only refers to a type, but is being used as a value here.

此外,我应该能够以某种方式指定类型:

<generic ...></generic>

最佳答案

泛型在编译时被删除,因此您不能使用类型参数 T 来创建 T 的新实例。但是,您可以将 T 的构造函数传递给类:

export class GenericComponent<T> {
// Take the constructor of T to the component constructor
constructor(private ctor: new ()=> T) {}
private array: T[];

addElement() {
const object = new this.ctor();
this.array.push(object);
}
}

class Item {}
class ItemComponent extends GenericComponent<Item>{
constructor(){
super(Item) // Pass in the constructor of the concrete type
}
}

关于angular - 如何传递通用类型并在 Angular 2 组件中创建此类型的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50818432/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com