[英]How to assign generic parent type to a generic subtype
這比 angular 更像是一個 typescript 問題。但讓我解釋一下情況。 我正在使用 angular 從父子組件傳遞數據。 父母有以下財產。
export class ParentComponent implements OnInit {
dataService: IService<ScrappedTypes>
}
ScrappedTypes
等於的地方。
type ScrappedTypes = ScrappedType1 | ScrappedType2 | ScrappedType3
並且IService
等於。
interface IService<T>{
data: T;
}
每個單獨的ScrappedType ie 1,2,3
本身就是不同的interfaces
。
我在 angular 中有 3 個不同的child components
。每個都代表一個 ScrappedType。 因此,例如在我的子組件中,我編寫了以下內容。
export class ScrappedType1Component implements OnInit {
dataService: IService<ScrappedType1>
}
export class ScrappedType2Component implements OnInit {
dataService: IService<ScrappedType2>
}
export class ScrappedType3Component implements OnInit {
dataService: IService<ScrappedType3>
}
但是我收到以下錯誤。
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>'
目標是將 ScrappedTypes narrow
為ScrappedTypes
之一,以便能夠輕松訪問每個ScrappedTypes
的屬性。 如何以正確的方式實現這一點?
在 stackblitz 中要解決的最重要的錯誤是Type 'IService<ScrappedTypes>' is not assignable to type 'IService<ScrappedType1>'
。 忽略其他的。
很確定問題出在您的聯合類型上。
type ScrappedTypes = ScrappedType1 | ScrappedType2 | ScrappedType3
我想 typescript 告訴你的是,如果你輸入你的服務之一,那么它需要像 union ScrappedType1 | ScrappedType2 | ScrappedType3
這樣的類型。 ScrappedType1 | ScrappedType2 | ScrappedType3
ScrappedType1 | ScrappedType2 | ScrappedType3
不僅僅是其中之一。 可能解釋得不夠好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.