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

React TypeScript报ts(7053)错误 如何给interface添加字符串索引属性

解决方案

你遇到的TS7053错误是因为collapseStates初始推导类型为空对象{},该类型没有定义字符串类型的索引签名,不支持用字符串作为键访问/赋值。按以下步骤修改即可:

1. 修正AA接口定义

在原有AA接口中添加collapseStates字段,指定字符串索引、布尔值的类型:

interface AA{
  action: "sites" | "analysers";
  actionArgs?: string;
  name: string;
  identifier: string;
  // 新增字段:键为字符串,值为布尔类型
  collapseStates: { [key: string]: boolean };
}

如果你的collapseStates是可选字段,可以在字段名后加问号:collapseStates?: { [key: string]: boolean };

2. 补全useState初始化参数

原有初始化代码只传了actionArgs和collapseStates,缺少AA接口要求的action、name、identifier必填字段,需要从props中获取:

let [state, setState] = useState<AA>({
  action: props.action,
  name: props.name,
  identifier: props.identifier,
  actionArgs: props.actionArgs,
  collapseStates: {} ,
});

3. 优化initialize函数类型定义

给collapseStates变量显式指定类型,避免隐式any推导:

const initialize = () => {
  // 显式指定类型,消除索引赋值报错
  let collapseStates: { [key: string]: boolean } = {};
  articles.map((el: AA) => {
    collapseStates[`${el.name}${el.identifier}`] = true;
    return;
  });
  setState({
    ...state,
    collapseStates: collapseStates,
  });
};

可选优化

补全handleExpandClick的参数类型、以及setState的字段展开逻辑,避免丢失state其他属性:

const handleExpandClick = (event: React.MouseEvent, key: string) => {
  setState({
    ...state,
    collapseStates: {
      ...state.collapseStates,
      [key]: !state.collapseStates[key],
    },
  });
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 17:39:03