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,
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题