Error reported in TypeScript: Element implicitly has type "any" because expressions of type "XXX" cannot be used for index types.

When using key-value pairs for matching, ts will report an error that the element has any type.

example:

let obj = {
    
    
  1: '轻微',
  2: '中等',
  3: '严重'
}
let variable = '这是'
// let res = obj[variable]  // 这里会报错

// 解决办法:声明一下键值对的类型
type objType = {
    
    
  1:string|number;
  2:string|number;
  3:string|number;
  [propName: string]: string;
}
let res = obj[variable as keyof objType]

Guess you like

Origin blog.csdn.net/Y1914960928/article/details/133132977