![](/img/trans.png)
[英]TypeScript - A computed property name must be of type 'string', 'number', 'symbol', or 'any'
[英]Typescript - An index expression argument must be of type 'string', 'number', 'symbol' or 'any'
我使用的是Typescript 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
變量嗎? 如何輸入並同時對其進行解構?
PS我省略了不必要的代碼,所以如果事情沒有意義,請告訴我。
似乎TypeScript無法正確猜測類型,因此我們可以使用顯式類型聲明來幫助它:
// .forEach( ([channel, color]) => {
.forEach( ([channel, color]: [string, string]) => {
甚至,如果顏色的類型更具體,例如:
const colors: any [] = ...
應該有助於確保索引/鍵通道和支持類型的顏色
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.