打字稿-参数类型为'string'

时间:2020-03-17 18:54:39

标签: javascript reactjs typescript

用Java语言实现的事情很简单:

interface Person {
  id: number
  red: number
  green: number
  blue: number
  buckets: Array<BucketType>
  // Does the index signature go here? What does it look like?
  // I haven't seen any "standard" way of doing this
}

interface BucketType {
  color: string,
  weight: number
}

const personA = {
  id: 123,
  red: 4,
  green: 5,
  blue: 6,
  buckets: [
    {
      color: 'Blue',
      weight: 4
    }
  ]
}
const personB = {
  id: 456,
  red: 7,
  green: 8,
  blue: 9,
  buckets: [
    {
      color: 'Red',
      weight: 10
    }
  ]
}
const people = [ personA, personB ]

for (let person of people) {
  for (let bucket of person.buckets) {
    console.log(bucket.weight) // 4, then 10
    console.log(bucket.color)  // 'Blue', then 'Red'
    bucket.weight += person[bucket.color.toLowerCase()] // ERROR: NO INDEX SIGNATURE!!!! (Typescript)
    console.log(bucket.weight) // In pure Javascript, this logs '10', then '17'
  }

}

老实说,地狱。如何为我的人员类型添加“索引签名”,这样我才能继续生活?

道歉的道歉,我没办法进步了,然后是TYPESCRIPT!

1 个答案:

答案 0 :(得分:3)

Typescript类型检查器在抱怨,因为它无法检查您的代码不会导致错误。 Typescript类型检查器无法读取字符串“ Red”和“ Blue”的值,并且知道如果它们是小写字母,则它们匹配对象上的属性。这只能在运行时完成,而不能在类型检查时完成。

因此,您必须向编译器提示bucket.color.toLowerCase()的可能结果如下:

bucket.weight += person[bucket.color.toLowerCase() as 'red'|'blue'|'green'];