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!!!
The error "No index signature with a parameter of type 'string' was found on type" occurs when we use a value of type string to index an object with specific keys. To solve the error, type the string as one of the object's keys using keyof typeof obj .
The "Type 'string' is not assignable to type" TypeScript error occurs when we try to assign a value of type string to something that expects a different type, e.g. a more specific string literal type or an enum. To solve the error use a const or a type assertion.
The index signature is a fitting way to handle objects with properties we know nothing about. Its syntax describes a regular property, but instead of writing a standard property name, we define the type of keys and the properties.
The error "Type is not assignable to type 'never'" occurs when we declare an empty array without explicitly typing it and attempt to mutate the array. To solve the error, explicitly type the empty array, e.g. const arr: string[] = []; .
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'];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With