简体   繁体   中英

Typescript - An index expression argument must be of type 'string', 'number', 'symbol' or 'any'

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?

PS 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, eg:

const colors: any [] = ...

should help to assure, that indexes/keys channel and color of supported types

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM