TypeScript踩坑之TS7053的问题及解决

这篇文章主要介绍了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(); 

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持0133技术站。

以上就是TypeScript踩坑之TS7053的问题及解决的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » Vue.js 教程