React-Redux-Typescriptコードがいくつかあり、APIから結果を取得して、応答オブジェクトのインターフェイスを作成しようとしています。ここに私のサンプルデータがあります:
const exampleState: ExampleState = {
loading: false,
products: {
"id": 11001,
"campus": "hrnyc",
"name": "Camo Onesie",
"slogan": "Blend in to your crowd",
"description": "The So Fatigues will wake you up and fit you in. This high energy camo will have you blending in to even the wildest surroundings.",
"category": "Jackets",
"default_price": "140.00",
"created_at": "2021-01-12T21:17:59.200Z",
"updated_at": "2021-01-12T21:17:59.200Z",
"features": [
{
"feature": "Fabric",
"value": "Canvas"
},
{
"feature": "Buttons",
"value": "Brass"
}
]
}
};
これがこのオブジェクトのインターフェースです:
export interface Featured {
"id": number
"campus": string,
"name": string,
"slogan": string,
"description": string,
"category": string,
"default_price": string,
"created_at": string,
"updated_at": string,
"features": [
{
"feature": string,
"value": string
}
]
}
レデューサー内で次のエラーが発生します。
TypeScript error in /Users/theo/Desktop/hrnyc34-fec-falcullele/my-app/src/reducers/singleProductReducer.ts(20,5):
Type '[{ feature: string; value: string; }, { feature: string; value: string; }]' is not assignable to type '[{ feature: string; value: string; }]'.
Types of property 'length' are incompatible.
Type '2' is not assignable to type '1'. TS2322
18 | "created_at": "2021-01-12T21:17:59.200Z",
19 | "updated_at": "2021-01-12T21:17:59.200Z",
> 20 | "features": [
| ^
21 | {
22 | "feature": "Fabric",
23 | "value": "Canvas"
私が知る限り、問題は「features」配列内に複数のオブジェクトがあるということです。この機能配列には、最大で12個のオブジェクトが含まれる可能性があります。このタイプスクリプトエラーを修正するにはどうすればよいですか?
指定したタイプfeature
はタプルです。これは、要素が既知のタイプを持つ固定長配列です。以下はあなたが望むものです:
type FeatureType = {
"feature": string,
"value": string
}
export interface Featured {
"id": number
"campus": string,
"name": string,
"slogan": string,
"description": string,
"category": string,
"default_price": string,
"created_at": string,
"updated_at": string,
"features": FeatureType[]
}
(注:読みやすさのために「機能」を型エイリアスに抽出しましたが、これを行う必要はありません)
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加