key值读取对象报错
大约 4 分钟
key 值读取对象报错
问题描述
通过 obj[key]
读取对象报错:元素隐式具有 “key” 类型,因为类型为 “string” 的表达式不能用于索引类型
解决方法
方法 1 (不推荐)
在 tsconfig.json 文件中加入如下代码,意思是:抑制隐式任何索引错误
{
"compilerOptions": {
"suppressImplicitAnyIndexErrors": true
}
}
若发现加入上述代码后,tsconfig.json
报错:
Option 'suppressImplicitAnyIndexErrors' is deprecated and will stop functioning in TypeScript 5.5. Specify compilerOption '"ignoreDeprecations": "5.0"' to silence this error.
接着加入代码:"ignoreDeprecations": "5.0"
{
"compilerOptions": {
"ignoreDeprecations": "5.0",
"suppressImplicitAnyIndexErrors": true
}
}
方法 2 (推荐)
为对象添加 interface
,并添加[name: string]: string
interface IRouters {
[name: string]: string;
Vue2: string;
Vue3: string;
}
const routers: IRouters = {
Vue2: '/app1',
Vue3: '/app2',
};
const handleClick: MenuProps['onClick'] = (e) => {
console.log('click', e);
router.push({
path: routers[e.key],
});
};