Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 如何将泛型父类型指定给泛型子类型_Angular_Typescript - Fatal编程技术网

Angular 如何将泛型父类型指定给泛型子类型

Angular 如何将泛型父类型指定给泛型子类型,angular,typescript,Angular,Typescript,这与其说是一个角度问题,不如说是一个打字问题。但让我解释一下情况。我使用angular将数据从父组件传递到子组件。父对象具有以下属性 export class ParentComponent implements OnInit { dataService: IService<ScrappedTypes> } 而IService等于 type ScrappedTypes = ScrappedType1 | ScrappedType2 | ScrappedType3 inte

这与其说是一个角度问题,不如说是一个打字问题。但让我解释一下情况。我使用angular将数据从父组件传递到子组件。父对象具有以下属性

export class ParentComponent implements OnInit {
    dataService: IService<ScrappedTypes>
}
IService
等于

type ScrappedTypes = ScrappedType1 | ScrappedType2 | ScrappedType3
interface IService<T>{
  data: T;
}
但是我得到了以下错误

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>'
类型“IService”不可分配给类型“IService”
类型“IService”不可分配给类型“IService”
类型“IService”不可分配给类型“IService”
目标是
报废类型缩小到报废类型之一,以便能够轻松访问每个
报废类型的属性。如何以正确的方式实现这一点


stackblitz内部要解决的最重要错误是
类型“iSeries设备”不能分配给类型“iSeries设备”
。忽略其他问题。

很确定问题出在您的联合类型上

类型报废类型=报废类型1 |报废类型2 |报废类型3


我认为typescript告诉您的是,如果您键入一项服务,那么它需要像union
ScrasedType1 | ScrasedType2 | ScrasedType3
那样键入,而不仅仅是其中一项。可能无法解释得很好。

请考虑修改这个问题中的代码,以便构成一个当它落入独立IDE时,清楚地表明你所面临的问题。这将允许那些想要帮助您的人立即着手解决问题,而无需首先重新创建问题。它将使您得到的任何答案都可以根据定义良好的用例进行测试。@jcalz这个问题的stackblitz这个问题似乎与我不太清楚的angular有关;也许有人能回答;我可以看到TypeScript问题:您的
AppComponent
不是,因此编译器无法基于检查
switchValue
来缩小其类型。TS不能声明
是有区别的联合,尽管您可以模拟这种行为。但这看起来无论如何都会阻止你。所以我能想到的最接近的方法就是使用。。。喜欢如果这对你有用的话,我也许可以写一个答案。如果没有,也许会有更好的事情发生。谢谢你,嗨,理查德。我知道错误,但我在问正确的方法来处理这个问题。正确的方法是什么
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>'