ts语法下使用a[b],报错error TS7053: Element implicitly has an 'any' type

634 阅读1分钟

问题如标题:

  • 在node.js中运行ts格式的代码,出现类型问题。
  • 错误信息是:error TS7053: Element implicitly has an 'any' type

报错部分代码:

const hashmap = {
    name:'yuyuan',
    age:'18',
    nation:'China',
    hometown:'HunanProvince'
}
type Select = {name:string,height:string}
const select = {name:'yuan',height:'180cm'}
if(select.name){consol.log(hashmap[select.name])}

解决方法:

① keyof
const hashmap:Hashmap = {
    name:'yuyuan',
    age:18,
    nation:'China',
    hometown:'HunanProvince'
}
type Hashmap = {  //声明类型
    name:string,
    age:number,
    nation:string,
    hometown:string
}
type Map = keyof Hashmap  //keyof
type Select = {name:Map,height:string} //改为keyof类型
const select = {name:'yuan',height:'180cm'}
if(select.name){consol.log(hashmap[select.name])}
② 声明key的类型
const hashmap = {
    name:'yuyuan',
    age:18,
    nation:'China',
    hometown:'HunanProvince'
}
type Hashmap = {  //声明类型
   [K:string]:string 
}
type Select = {name:string,height:string} 
const select = {name:'yuan',height:'180cm'}
if(select.name){consol.log(hashmap[select.name])}