Types such as string, number, and any in Ts cannot be used as indexes, how to deal with them?

insert image description here


Introduction

Types such as string, number, and any in Ts cannot be used as indexes, how to deal with them?
Error: 元素隐式具有“any”类型,因为类型为“number”的表达式不能用于索引类型“[***”。在类型“[ ***”上找不到具有类型为“number"的参数的索引签名。 ts(7053)
use of keyof

question

Types such as string, number, and any in Ts cannot be used as indexes, how to deal with them?

const handerField = (item: number) => {
    
    
   caselist= data.showList[item]//报错
}

Elements implicitly have type any, because type number cannot be used to index {} types.

Solution

method 1

const handerField = (item: number) => {
    
    
   caselist= (data.showList as any)[item];
}

Method 2

const handerField = (item: number) => {
    
    
   caselist= data.showList [item as keyof typeof data.showList ]
}

Method 3

const handerField =  function <T extends object, K extends keyof T>(obj: T, key: K) {
    
    
  return obj[key];
}

Guess you like

Origin blog.csdn.net/weixin_48998573/article/details/130127109