[英]How to assign generic parent type to a generic subtype
This is more of a typescript question than angular. But let me explain the situation.这比 angular 更像是一个 typescript 问题。但让我解释一下情况。 I am using angular to pass data from a parent-to-child component.
我正在使用 angular 从父子组件传递数据。 The parent has the following property.
父母有以下财产。
export class ParentComponent implements OnInit {
dataService: IService<ScrappedTypes>
}
Where ScrappedTypes
is equal to. ScrappedTypes
等于的地方。
type ScrappedTypes = ScrappedType1 | ScrappedType2 | ScrappedType3
and IService
is equal to.并且
IService
等于。
interface IService<T>{
data: T;
}
Each individual ScrappedType ie 1,2,3
are different interfaces
themselves.每个单独的
ScrappedType ie 1,2,3
本身就是不同的interfaces
。
I've 3 different child components
in angular. Each representing a ScrappedType.我在 angular 中有 3 个不同的
child components
。每个都代表一个 ScrappedType。 So for example in my child components, I write the following.因此,例如在我的子组件中,我编写了以下内容。
export class ScrappedType1Component implements OnInit {
dataService: IService<ScrappedType1>
}
export class ScrappedType2Component implements OnInit {
dataService: IService<ScrappedType2>
}
export class ScrappedType3Component implements OnInit {
dataService: IService<ScrappedType3>
}
But I get the following error.但是我收到以下错误。
Type 'IService<ScrappedTypes>' is not assignable to type 'IService<ScrappedType1>'
Type 'IService<ScrappedTypes>' is not assignable to type 'IService<ScrappedType2>'
Type 'IService<ScrappedTypes>' is not assignable to type 'IService<ScrappedType3>'
The goal is to narrow
down the ScrappedTypes
to one of the ScrappedType to be able to access the properties of each ScrappedTypes
easily.目标是将 ScrappedTypes
narrow
为ScrappedTypes
之一,以便能够轻松访问每个ScrappedTypes
的属性。 How can this be accomplished in the correct way?如何以正确的方式实现这一点?
The most important error to resolve inside the stackblitz is Type 'IService<ScrappedTypes>' is not assignable to type 'IService<ScrappedType1>'
.在 stackblitz 中要解决的最重要的错误是
Type 'IService<ScrappedTypes>' is not assignable to type 'IService<ScrappedType1>'
。 Ignore the other ones.忽略其他的。
Pretty sure the problem is with your union type.很确定问题出在您的联合类型上。
type ScrappedTypes = ScrappedType1 | ScrappedType2 | ScrappedType3
I think what typescript is telling you is that if you type one of your services then it needs to be type like the union ScrappedType1 | ScrappedType2 | ScrappedType3
我想 typescript 告诉你的是,如果你输入你的服务之一,那么它需要像 union
ScrappedType1 | ScrappedType2 | ScrappedType3
这样的类型。 ScrappedType1 | ScrappedType2 | ScrappedType3
ScrappedType1 | ScrappedType2 | ScrappedType3
not just one of them. ScrappedType1 | ScrappedType2 | ScrappedType3
不仅仅是其中之一。 Probably not explaining it well enough.可能解释得不够好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.