Redux Toolkit对象数组类型与接口设置错误求助
修复TypeScript错误TS2339:Property 'snippet' does not exist on type '{}'
问题根源
PostState接口中cartegory的类型定义为cartegory | {}[],其中{}[]会让TypeScript判定数组元素可能是空对象,遍历访问snippet时触发类型错误。- 你定义的
cartegory类型本身已经是数组类型(末尾带有[]),在PostState中重复声明数组类型属于冗余操作。 - 原类型定义中
position: 0是固定值类型,不符合实际数据场景,应该定义为number类型。
具体修复步骤
1. 修正类型定义的结构与命名
遵循TypeScript大驼峰命名规范,拆分单个分类项和数组类型,避免类型与变量名混淆:
// 单个分类项的类型 export interface CategoryItem { kind: string; etag: string; id: string; snippet: { publishedAt: string; channelId: string; title: string; description: string; thumbnails: { default: { url: string; width: number; height: number }; medium: { url: string; width: number; height: number }; high: { url: string; width: number; height: number }; standard: { url: string; width: number; height: number }; maxres: { url: string; width: number; height: number }; }; channelTitle: string; playlistId: string; position: number; // 修正为number类型,而非固定值0 resourceId: { kind: string; videoId: string }; videoOwnerChannelTitle: string; videoOwnerChannelId: string; }; } // 分类数组类型 export type Category = CategoryItem[];
2. 修正PostState接口的类型声明
移除冗余的| {}[],直接使用定义好的Category类型:
interface PostState { loading: boolean; error: string | null; data: youtubeResponse | null; cartegory: Category; // 明确为Category类型 }
3. 优化Redux Toolkit中的赋值逻辑
原代码存在重复添加相同items的问题,根据需求调整赋值逻辑:
.addCase(youtubeList_Playlist.fulfilled, (state, action: PayloadAction<youtubeResponse>) => { state.loading = false; state.data = action.payload; // 若需要累加历史数据,用当前数组合并新items state.cartegory = [...state.cartegory, ...action.payload.items]; // 若只保留当前请求数据,直接赋值 // state.cartegory = action.payload.items; })
4. 组件中优化遍历判断
用数组长度判断替代空值判断,更准确过滤空数组场景:
{cartegory.length > 0 && cartegory.map((value, index) => { return ( <Tab label={value.snippet.title} {...a11yProps(index)} key={value.id} /> ) })}
内容的提问来源于stack exchange,提问作者EthanKyle
相关产品推荐
相关产品推荐

