在类型"{}"上找不到具有 'string' 类型参数的索引签名.ts(7053)



我是react typescript的新手,这里我有props和它的类型,一切都很好,除了这部分:+ el.name + el。标识符]= true;它给出错误:元素隐式具有'any'类型,因为'string'类型的表达式不能用于索引类型'{}'。在类型"{}"上找不到带有"字符串"类型参数的索引签名。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,
});
};
}

您可以键入collapseStates作为Record:

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

相关内容