2016-02-25 44 views
3

我用的打字稿1.7.5和我遇到以下情况An index expression argument must be of type 'string', 'number', or 'any'错误:打字稿 - 索引表达式参数的类型必须是“字符串”,“数字”,“符号”或“任意”

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(); 
}); 

是否是导致错误的channel变量?我怎样才能在同一时间输入并解构它?

P.S.我已经省略了不必要的代码,所以如果有什么不合理的话让我知道。

+0

的索引/键通道和颜色为什么是U将数组传递给'forEach'? – giannisf

+0

你的意思是?第二个'forEach'? – XeniaSis

回答

3

看来,打字稿是不能正确猜测类型,所以我们可以用明确的类型声明帮助它:

// .forEach(([channel, color]) => { 
.forEach(([channel, color]: [string, string]) => { 

甚至,如果颜色的种类将更加具体,如:

const colors: any [] = ... 

应有助于确保,即支持的类型

+0

完美!谢谢,我不知道如何输入解构变量 – XeniaSis

+0

是的;)伟大的,如果这有帮助无论如何,享受TS,先生... –

相关问题