好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

TypeScript踩坑之TS7053的问题及解决

Ty PE Script踩坑之TS7053

错误:TS7053: Element implic IT ly has an ‘any’ type because ex Press ion of type ‘string’ can’t be used to index type xxx

在 vue 中如果用 TypeScript 写类似如下的代码,用 []定位对象中的某一个属性,因为TypeScript的类型检查,编译会报TS7053错误

@H_ 512 _23@const Map1 = { a: '1', b: '2', c: '3' } const Map2 = { d: '1', e: '2', f: '3' } function test (): void { let str = ' abc def'; let key = str.s ub str(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: {[ PR opN am e: 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();

总结

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

您可能感兴趣的 文章 : 关于TypeScript的踩坑记录 typescript+vite项目配置别名的方法实现 vue项目中使用ts(typescript)入门教程

总结

以上是 为你收集整理的 TypeScript踩坑之TS7053的问题及解决 全部内容,希望文章能够帮你解决 TypeScript踩坑之TS7053的问题及解决 所遇到的问题。

如果觉得 网站内容还不错, 推荐好友。

查看更多关于TypeScript踩坑之TS7053的问题及解决的详细内容...

  阅读:36次