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();
解決方法
就是另寫一個函數(shù)判斷一下對象有沒有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();
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Vue實現(xiàn)Hover功能(mouseover與mouseenter的區(qū)別及說明)
這篇文章主要介紹了Vue實現(xiàn)Hover功能(mouseover與mouseenter的區(qū)別及說明),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-10-10
Vue-Cli如何在index.html中進行環(huán)境判斷
這篇文章主要介紹了Vue-Cli如何在index.html中進行環(huán)境判斷問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-03-03
vue項目webpack中Npm傳遞參數(shù)配置不同域名接口
這篇文章主要介紹了vue項目webpack中Npm傳遞參數(shù)配置不同域名接口,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-06-06
Vue啟動失敗報錯:Module?not?found:?Error:?Can‘t?resolve?&apos
這篇文章主要給大家介紹了關(guān)于Vue啟動失敗報錯:Module?not?found:?Error:?Can‘t?resolve?'less-loader'解決的相關(guān)資料,文中通過圖文介紹的非常詳細,需要的朋友可以參考下2023-03-03

