You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Redux Toolkit对象数组类型与接口设置错误求助

修复TypeScript错误TS2339:Property 'snippet' does not exist on type '{}'

问题根源

  1. PostState接口中cartegory的类型定义为cartegory | {}[],其中{}[]会让TypeScript判定数组元素可能是空对象,遍历访问snippet时触发类型错误。
  2. 你定义的cartegory类型本身已经是数组类型(末尾带有[]),在PostState中重复声明数组类型属于冗余操作。
  3. 原类型定义中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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 04:50:33