Skip to content
Advertisement

Getting error while referencing the type as index

I have an array of objects with the following structure

JavaScript

I need to take each key within each object inside array and form an array out of it. Basically grouping based on the key present in all the objects.If the object has no “values” it should return 0 across the val1,val2,val3.

JavaScript

Here I am passing an string, that will be used inside reduce.I am getting this error any cannot be used as index whenever I pass in a dynamically string that will be used inside a reduce function whenever typescript is enabled.

The code works just fine, but after I upgraded to the latest TS it is throwing the error and it does not compile

Can someone help me?

I have tried the following:

JavaScript

Advertisement

Answer

Using reduce with dynamic keys with Typescript can be ugly and is arguably not appropriate even in Javascript when creating a single object. Consider creating the object you put the data into outside the loop instead – one whose properties are the names (High, etc) and values are the number arrays. Push to the number array on each iteration (pushing 0 if the property doesn’t exist), creating the property with the array first if needed. After looping, turn the object into an array of objects:

JavaScript

Compiled output:

JavaScript

If the valueObj key is dynamic, it gets a lot uglier. Best I could figure out was, when iterating over an array item, if it has the own property of the object key, then to assert that the array item is of type { [possibleKeyForObj: string]: { [key: string]: number } }, allowing you to access the nested property:

JavaScript
Advertisement