【问题标题】:No index signature with a parameter of type 'string' was found on type '{}'.ts(7053) [duplicate]在“{}”.ts(7053) 类型上找不到具有“字符串”类型参数的索引签名 [重复]
【发布时间】:2021-12-04 21:48:28
【问题描述】:

我是 react typescript 的新手,这里我有 props 及其类型,除了这部分之外一切都很好: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,
    });
  };
  }

【问题讨论】:

  • 任何帮助表示赞赏
  • 任何帮助表示赞赏

标签: javascript html reactjs typescript react-hooks


【解决方案1】:

您可以将collapseStates 输入为Record

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2020-01-06
  • 1970-01-01
  • 1970-01-01
  • 2021-10-16
  • 1970-01-01
  • 2019-10-27
  • 2021-11-27
  • 2021-06-27
相关资源
最近更新 更多