目录
- TypeScript踩坑之TS7053
- 解决方法
- 总结
TypeScript踩坑之TS7053
错误:TS7053: Element implicitly has an ‘any’ type because expression of type ‘string’ can’t be used to index type xxx
在 vue 中如果用 TypeScript 写类似如下的代码,用 []定位对象中的某一个属性,因为TypeScript的类型检查,编译会报TS7053错误
const Map1 = {
a: '1',
b: '2',
c: '3'
}
const Map2 = {
d: '1',
e: '2',
f: '3'
}
function test(): void {
let str = 'abcdef';
let key = str.substr(1, 1);
console.log(Map1[key]);
console.log(Map2[key]);
}
test();
解决方法
就是另写一个函数判断一下对象有没有key那个属性
const Map1 = {
a: '1',
b: '2',
c: '3'
}
const Map2 = {
d: '1',
e: '2',
f: '3'
}
function isValidKey(key: string, obj: {[propName: string]: amy}): key is keyof typeof obj {
return key in obj;
}
function test(): void {
let str = 'abcdef';
let key = str.substr(1, 1); // 'b'
if (isValidKey(key, Map1) console.log(Map1[key]); // '2'
if (isValidKey(key, Map2) console.log(Map2[key]); // 不会输出
}
test();
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

评论(0)