Reputation: 2305
Things are SIMPLE in Javascript:
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'
}
}
Honestly what the hell. How do I add an "index signature" to my person types so I can get on with my life?
Apologies for textually whining, I'm just depleted from making progress then TYPESCRIPT!!!
Upvotes: 8
Views: 12598
Reputation: 2014
The Typescript type checker is complaining because it cannot check that your code will not result in an error. The Typescript type checker cannot read the values of the string 'Red' and 'Blue' and know that if they are lowercased they match a property on your object. This can only be done at runtime, not at type checking time.
You must thus hint to the compiler what the possible outcomes of bucket.color.toLowerCase()
might be like this:
bucket.weight += person[bucket.color.toLowerCase() as 'red'|'blue'|'green'];
Upvotes: 14