首页 > 解决方案 > 在类型 '{}'.ts(7053) 上找不到具有类型参数的索引签名

问题描述

我是反应打字稿的新手,这里我有道具及其类型,除了这部分之外一切都很好:collapseStates["" + el.name + el.identifier] = true; 它给出错误:元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“{}”。在类型 '{}'.ts(7053) 上找不到具有类型参数的索引签名

将:collapseStates = {} 添加到接口 AA 的正确方法是什么?如您所见,它应该包含字符串collapseStates["" + el.name + el.identifier] 任何帮助或建议表示赞赏

  interface AA{
  action: "sites" | "analysers";
  actionArgs?: string;
  name: string;
  identifier: string;
}
  
  const Article: React.FC<AA> = (props) => {

  let [state, setState] = useState<AA>({
    actionArgs: props.actionArgs,
    collapseStates: {} ,
  });
 const handleExpandClick = (event, key) => {
setState({
  collapseStates: {
    ...state.collapseStates,
    [key]: !state.collapseStates[key],
  },
});
  };

 const initialize = () => {
    let collapseStates = {};
    articles.map((el: AA) => {
      collapseStates["" + el.name + el.identifier] = true;
      return;
    });

    setState({
      ...state,
      collapseStates: collapseStates,
    });
  };
  }

标签: javascripthtmlreactjstypescriptreact-hooks

解决方案


您可以键入collapseStatesRecord

interface AA{
  ...
  collapseStates: Record<string,boolean>;
}

推荐阅读