简体   繁体   English

在角度分量中指定通用变量的类型

[英]Specifying type of generic variable in angular component

I am trying to create a generic component which can expect data of two types only:我正在尝试创建一个通用组件,它只能期望两种类型的数据:

interface X{
    name: string,
    path: string,
    type: string,
}

interface Y{
    name: string,
    path: string,
}

Both types X,Y have two common properties and X has one extra.两种类型 X,Y 都有两个共同的属性,而 X 有一个额外的属性。 Now I am defining the type this way:现在我以这种方式定义类型:

export class MyComponent<T extends X | Y> implements OnInit{
    @Input() data: T[];
    func(item: T){
        let temp = this.data.find(x => x.name === item.name);
        <<....some code....>>
    }
}

Calling this from the parent component this way:以这种方式从父组件调用它:

<my-component [data]="xList"></my-component>     <!-- xList: X[] -->
<my-component [data]="yList"></my-component>     <!-- yList: y[] -->

This is working fine but I am not sure if this <T extends X | Y>这工作正常,但我不确定这个<T extends X | Y> <T extends X | Y> is the correct way to do this or not. <T extends X | Y>是执行此操作或不执行此操作的正确方法。 Can anybody please suggest the best approach here?有人可以在这里建议最好的方法吗? Can we write something like where T implements X | Y我们可以写一些类似where T implements X | Y吗? where T implements X | Y in Typescript? where T implements X | Y在打字稿中?

Or should I just use @Input() data: any[];或者我应该只使用@Input() data: any[]; ? ?

我认为这很好,但我会做T extends Y只是因为type键在 X 上是额外的,如果我们向它提供 Y 类型数组的输入并且组件与type键混淆,则该组件会损坏。

I don't think the Angular framework would know the generic argument T when it instantiate MyComponent .我认为 Angular 框架在实例化MyComponent时不会知道通用参数 T 。 the only thing i can think of is to get an instance of the component at runtime and try to set the generic type yourself which will make any diffrence as the MyComponent would be instanciated already and the @Input() data would be set.我唯一能想到的是在运行时获取组件的实例并尝试自己设置泛型类型,这将产生任何差异,因为MyComponent已经实例化并且@Input() data将被设置。

I think you should just write @Input() data: X[] | Y[]我认为你应该只写@Input() data: X[] | Y[] @Input() data: X[] | Y[] . @Input() data: X[] | Y[]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM