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.
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
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