Next.js + TypeScriptでシステムを作っています。
componentにpropsを渡す部分で Type 'CategoryDetail[]' is missing the following properties
のエラーが出ているのでそれを消したいのですが、どのように解消したら良いでしょうか。
設計として少し特殊なのが、APIからのjsonレスポンスの型がカテゴリによって異なる点です。
具体的には、以下のように details
の配列には Details
が入るのですが、 Details
の中の category_details
は category_name
によって Shirt
だったり Bag
だったりします。
json
1{ 2 "data": { 3 "id": 1, 4 "details": [ 5 { 6 "id": 1, 7 "category_name": "shirt", 8 "category_detail": { 9 "id": 1, 10 "size": "small", 11 "color": "white" 12 } 13 }, 14 { 15 "id": 2, 16 "category_name": "bag", 17 "category_detail": { 18 "id": 13, 19 "width": 30, 20 "height": 15 21 } 22 }, 23 { 24 "id": 3, 25 "category_name": "shirt", 26 "category_detail": { 27 "id": 45, 28 "size": "large", 29 "color": "pink" 30 } 31 } 32 ] 33 } 34}
typescript
1export interface Box { 2 id: number; 3 details: Details[]; 4} 5 6export interface Details { 7 id: number; 8 category_name: string; 9 category_detail: CategoryDetail[]; 10} 11 12export interface Shirt { 13 id: number; 14 size: string; 15 color: string; 16} 17 18export interface Bag { 19 id: number; 20 width: number; 21 height: number; 22} 23 24export type CategoryDetail = Shirt | Bag;
上記の前提で、問題のエラーが出ている箇所は以下です。
typescript
1const Foo: NextPage = () => { 2 const { box } = useFetchBox(); 3 4 return ( 5 <div> 6 {box.details.map((detail) => ( 7 {detail.category_name === "shirt" && <ShirtDetail categroy_detail={detail.category_detail} />} // error: Type 'CategoryDetail[]' is missing the following properties from type 'ShirtDetail': id, size, color 8 {detail.category_name === "bag" && <BagDetail categroy_detail={detail.category_detail} />} // error: Type 'CategoryDetail[]' is missing the following properties from type 'BagDetail': id, width, height 9 ))} 10 </div> 11 ) 12}
detail.category_name === "shirt" &&
のように指定した上で <ShirtDetail />
にpropsを渡そうとしているので動きそうなものなんですが、上記の通りlintエラーが出てしまいます。なにがいけないのでしょうか?( interface
の定義方法がなにかしら誤っているのか...?)
自分では修正方法の見当がつかないため、アドバイスいただけますと幸いです。よろしくお願い致します。
回答1件
あなたの回答
tips
プレビュー