简体   繁体   中英

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. I am using angular to pass data from a parent-to-child component. The parent has the following property.

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

Where ScrappedTypes is equal to.

type ScrappedTypes = ScrappedType1 | ScrappedType2 | ScrappedType3

and IService is equal to.

interface IService<T>{
  data: T;
}

Each individual ScrappedType ie 1,2,3 are different interfaces themselves.

I've 3 different child components in angular. Each representing a 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. How can this be accomplished in the correct way?

Stackblitz

The most important error to resolve inside the stackblitz is 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 ScrappedType1 | ScrappedType2 | ScrappedType3 ScrappedType1 | ScrappedType2 | ScrappedType3 not just one of them. Probably not explaining it well enough.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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