Reputation: 2354
I am using Typescript 1.7.5 and I encountered the An index expression argument must be of type 'string', 'number', or 'any'
error on the following situation:
const settings: any = {};
_.forEach(data, (d, name: string) => { //data is just an object
settings[name] = {};
const colors = ColorGenerator.generateColors(Object.keys(d.ch).length);
_(d.ch)
.keys()
.zip(colors)
.forEach(([channel, color]) => {
// name and channel are both strings
settings[name][channel] = { // this line is throwing the error
channel,
color,
visible: true
};
}).value();
});
Is it the channel
variable that's causing the error? How can I type it and destructure it at the same time?
P.S. I have omitted unnecessary code so if something is not making sense let me know.
Upvotes: 3
Views: 1680
Reputation: 123861
It seems that TypeScript is not able to guess types properly, so we can help it with explicit type declaration:
// .forEach( ([channel, color]) => {
.forEach( ([channel, color]: [string, string]) => {
maybe even, if the type of colors will be more specific, e.g.:
const colors: any [] = ...
should help to assure, that indexes/keys channel and color of supported types
Upvotes: 3