发布于 4年前

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 类型可以解决,有没有更好的办法呢?

解决方案:

function getValue(arg: keyof typeof a)
©2020 edoou.com   京ICP备16001874号-3