目录typescript踩坑之TS7053解决方法总结TypeScript踩坑之TS7053 错误:TS7053: Element implicitly has an ‘
错误: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();
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。
--结束END--
本文标题: TypeScript踩坑之TS7053的问题及解决
本文链接: https://www.lsjlt.com/news/178266.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-01-12
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0