typescript 如何使用中括号获取对象的属性

示例:

const a = {
  item1: 'xxx',
  item2: 'xxx'
}

function getValue(arg: string) {
  return a[arg]
}

getValue('item1')

a[arg] 会报错:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ item1: string; item2: string; }'.

参数是 string 类型,不能用作对象 a 的索引。把 a 设置为 any 类型可以解决,有没有更好的办法呢?求教。

阅读 21.3k
3 个回答
function getValue(arg: keyof typeof a)

除了设置类型为any, 还可以在tsconfig.json中配置suppressImplicitAnyIndexErrorstrue

Suppress --noImplicitAny errors for indexing objects lacking index signatures.
See issue #1232 for more details.
新手上路,请多包涵
interface gameList {
    [key: string]: any,
}
推荐问题