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();
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论