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

TypeScript对象key属性类型错误求助:索引表达式类型不匹配

React TypeScript版Wordle克隆项目类型错误解决

问题描述

将JavaScript版Wordle教程迁移为TypeScript后,useWordGame.tsx中操作prevUsedKeys[l.key]的代码出现类型错误:

  • 初始化usedKeys为数组[]时,报错:Element implicitly has an 'any' type because index expression is not of type 'number'
  • 初始化usedKeys为对象{}时,报错:Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'

解决方案

1. 定义明确的类型约束

为按键状态对象定义类型,明确键为字母字符串,值为固定的颜色枚举:

type KeyColor = 'green' | 'yellow' | 'grey';
interface UsedKeys {
  [key: string]: KeyColor;
}

2. 修正状态初始化

给usedKeys的useState指定类型,确保初始值符合类型约束:

const [usedKeys, setUsedKeys] = useState<UsedKeys>({});

3. 修复状态更新逻辑

React状态是不可变的,不能直接修改prevUsedKeys,需创建新对象更新;同时修正类型断言和逻辑错误:

setUsedKeys(prevUsedKeys => {
  const newUsedKeys = { ...prevUsedKeys };
  formattedGuess.forEach(l => {
    const currentColor = newUsedKeys[l.key];

    if (l.color === 'green') {
      newUsedKeys[l.key] = 'green';
    } else if (l.color === 'yellow' && currentColor !== 'green') {
      newUsedKeys[l.key] = 'yellow';
    } else if (l.color === 'grey' && currentColor !== 'green' && currentColor !== 'yellow') {
      newUsedKeys[l.key] = 'grey';
    }
  });
  return newUsedKeys;
});

说明:原代码中currentColor !== ('green' || 'yellow')是逻辑错误,该表达式等价于currentColor !== 'green',需改为判断不等于两种颜色;同时将map替换为forEach,因为这里不需要返回数组。

4. 优化参数类型(可选但推荐)

原secretWord的类型string | null[]不符合业务逻辑,应改为string:

const useWordGame = (secretWord: string) => {
  // ...
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 04:18:24