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

React TypeScript中如何正确映射含对象数组参数的组件?

解决TypeScript中“Property 'score' does not exist on type 'Object'”的类型错误

核心问题根源

你把数组类型定义成Array<Object>,但TypeScript里的Object是最基础的宽泛类型,它不包含score这类自定义属性,因此在map操作中访问score时会触发类型校验错误。

正确解决步骤

1. 定义具体的对象类型

先给players数组中的每个玩家对象明确类型,字段要和实际数据(比如数据库返回的结构)匹配:

interface Player {
  id: number; // 示例字段:玩家ID
  score: number; // 你需要访问的score字段
  name: string; // 示例字段:玩家名称,按需添加其他字段
}

2. 定义包含players的父级数据类型

接着给gamesPlayed整体定义类型,明确它包含players数组:

interface GamePlayed {
  gameId: string; // 示例字段:游戏ID
  players: Player[]; // 这里使用刚才定义的Player类型数组
  gameTime: string; // 示例字段:游戏时间,按需补充其他字段
}

3. 给变量/数据来源指定类型

不管是硬编码的测试数据,还是从数据库获取的真实数据,都要绑定正确的类型:

// 硬编码示例
const gamesPlayed: GamePlayed[] = [
  {
    gameId: "game_001",
    players: [
      { id: 1, score: 95, name: "Alice" },
      { id: 2, score: 88, name: "Bob" }
    ],
    gameTime: "2024-05-20"
  }
];

// 数据库请求示例(以async函数为例)
async function fetchGamesFromDB(): Promise<GamePlayed[]> {
  const response = await fetch("/api/user/games");
  return response.json();
}

4. 正常执行map操作

现在对players数组做map时,TypeScript能准确识别player的类型,不会再报错:

gamesPlayed.forEach(game => {
  const scoreList = game.players.map(player => {
    // player类型为Player,可直接访问score等属性
    return `${player.name} 的得分:${player.score}`;
  });
  console.log(scoreList);
});

额外提示

  • 若数据库返回的字段存在可选情况,可在接口中用?标记可选字段,比如score?: number
  • 不要用any跳过类型检查,这会丢失TypeScript的类型安全优势,尽量保持类型精准

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 19:35:08