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

TypeScript类型不兼容与属性不存在错误排查求助

解决TypeScript类型不兼容与属性不存在错误

错误信息

类型“({ ItemName, ItemRarityStandard, count }: { ItemName: any; ItemRarityStandard: any; count: any; }) => string”的参数不能赋给类型“(value: unknown, index: number, array: unknown[]) => string”的参数。
参数“__0”和“value”的类型不兼容。
类型“unknown”不能赋给类型“{ ItemName: any; ItemRarityStandard: any; count: any; }”。

属性“count”在类型“unknown”上不存在。

问题根源

  1. reduce的初始值{}未指定类型,导致TypeScript无法推断counts的具体类型,最终Object.values(counts)被判定为unknown[],map阶段解构未知类型的属性自然触发报错。
  2. 代码中滥用any,丢失了TypeScript的类型检查能力,同时干扰了类型推断逻辑。

修复方案

先明确物品相关的类型定义,再修正reduce的类型标注,替换模糊的any为具体类型:

// 定义原始物品的类型接口
interface Item {
  ItemID: number;
  ItemName: string;
  ItemRarityStandard: string;
}

// 定义统计后的物品类型接口
interface ItemCount {
  count: number;
  ItemName: string;
  ItemRarityStandard: string;
}

const capitalise = (str: string) => str.replace(/\b[a-z]/g, (c) => c.toUpperCase());

// 假设data.Items的类型是Item[],若已有内置类型可直接替换
const counts = (data.Items as Item[])
  .toSorted((a, b) => b.ItemID - a.ItemID) // 保持原有排序逻辑
  .reduce((acc, { ItemID, ItemName, ItemRarityStandard }) => {
    acc[ItemID] ??= {
      ItemName,
      ItemRarityStandard,
      count: 0,
    };
    acc[ItemID].count++;
    return acc;
  }, {} as { [key: string]: ItemCount }); // 明确累加器的类型

const str = Object.values(counts)
  .map(({ ItemName, ItemRarityStandard, count }) => `${count}x ${capitalise(ItemName)} **${ItemRarityStandard}**`)
  .join("\n");

关键改动说明

  • 新增Item和ItemCount接口,明确数据结构,替代模糊的any类型。
  • 在reduce的初始值{}后添加类型断言as { [key: string]: ItemCount },让TypeScript明确累加器的类型,从而正确推断counts的类型。
  • 移除reduce参数中的any,改用Item接口,确保类型检查生效。
  • 如果data.Items本身已有定义好的类型,可以去掉as Item[]的类型断言。

内容的提问来源于stack exchange,提问作者Ladizi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 19:36:12