![](/img/trans.png)
[英]React typescript - Element implicitly has an 'any' type because expression of type 'string' can't be used to index type
[英]Typescript with React > Element implicitly has an 'any' type because expression of type 'string' can't be used to index
我在嘗試使用帶有 react 的 typescript 構建項目時遇到了這個問題。 這是來自打字稿的錯誤消息。
Enter code hereElement implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ time: string; EC_slab1: number; EC_slab2: number; EC_drain_PC: number; WC_slab1: number; WC_slab2: number; CO2air: number; HumDef: number; Rhair: number; Tair: number; EnScr: number; BlackScr: number; ... 4 more ...; Tout: number; }'.
No index signature with a parameter of type 'string' was found on type '{ time: string; EC_slab1: number; EC_slab2: number; EC_drain_PC: number; WC_slab1: number; WC_slab2: number; CO2air: number; HumDef: number; Rhair: number; Tair: number; EnScr: number; BlackScr: number; ... 4 more ...; Tout: number; }'. TS7053
20 | newObj[e] = [];
21 | }
> 22 | newObj[e].push(ele[e]);
| ^
23 | console.log(ele[e]);
24 | console.log(e);
25 | })`
似乎錯誤發生在帶有參數 ele 的內聯 22。
假設我有這個:
declare global {
type Dictionary<T> = { [key: string]: T };
}
let newObj: Dictionary<any> = {};
Data.dataset.forEach(ele => {
const keys = Object.keys(ele);
keys.forEach(e => {
// console.log
if(!newObj[e]){
newObj[e] = [];
}
newObj[e].push(ele[e]);
})
});
const options: Highcharts.Options = {
title: {
text: 'My chart'
},
yAxis: {
title: {
text: 'Baby boom'
}
},
series: [{
type: 'line',
name:'a',
data: [1, 2, 3]
}, {
type: 'line',
name:'b',
data: [11, 22, 3]
},{
type: 'line',
name:'c',
data: [1, 23, 53]
}],
}
const App = (props: HighchartsReact.Props) => <div>
<HighchartsReact
highcharts={Highcharts}
options={options}
{...props}
/>
</div>
export default App;
我試着在 TypeScript 文檔上到處尋找,但我怎么想怎么接口它才能接受 ele[e]??
看起來問題在於您嘗試使用類型為 any 的字符串作為索引。
newObj[e].push(ele[e]);
Data.dataset 是一個{}
字典,當將 forEach "ele" 作為字符串類型的鍵進行迭代以及循環類型為 number 的鍵時。 拋出異常是因為您嘗試使用字符串作為索引。 注意如果Datadataset
中的鍵是字符串類型,則 forEach 循環將打印字符串中的每個char
,即子字符串。 如果您嘗試將字典復制到新字典中。 可以通過以下方式實現。
let copy_db: Dictionary<any> = {};
// Loop over all the keys in the object
for (let prop in Data.dataset) {
// Make sure the object has this value, and not its prototype
if (Data.dataset.hasOwnProperty(prop)) {
// throws value into new dictionary
copy_db[prop] = (Data.dataset[prop];
// if you would like an empty value in the new dictionary, then you would add a else with copy_db[prop] = [];
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.