![](/img/trans.png)
[英]React typescript - Element implicitly has an 'any' type because expression of type 'string' can't be used to index type
[英]react typescript error - element implicitly has an any type because expression of type string cant be used to index type {}
我正在嘗試使用 typescript 在我的 React 項目中按 x 對數組進行分組,但出現以下錯誤:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.
No index signature with a parameter of type 'string' was found on type '{}'. TS7053
有人可以幫我定義它以消除 typescript 錯誤嗎? 我是 React 的新手。
這是錯誤的位置
const result = trades.reduce((groupedAccounts, trade) => {
const account = trade.pacct;
if (groupedAccounts[account] == null) groupedAccounts[account] = [];
groupedAccounts[account].push(trade);
return groupedAccounts;
}, {});
這是我從 another.ts 導出的界面
export interface TradeData {
id: number;
filedate: Date;
poffic: string;
pacct: string;
quantity: number;
sector: string;
psdsC1: string;
name: string;
bbsymbol: string;
last_price: number;
deltasettlement: number;
}
我確定這是我不明白的語法問題。
reduce
可以采用泛型來指定謂詞返回的內容(以及初始值的類型)。
由於初始值,此處將其推斷為{}
:
const result = trades.reduce((groupedAccounts, trade) => {
const account = trade.pacct;
if (groupedAccounts[account] == null) groupedAccounts[account] = [];
groupedAccounts[account].push(trade);
return groupedAccounts;
}, {});
您可能希望它是Record<string, TradeData[]>
:
const result = trades.reduce<Record<string, TradeData[]>>((groupedAccounts, trade) => {
const account = trade.pacct;
if (groupedAccounts[account] == null) groupedAccounts[account] = [];
groupedAccounts[account].push(trade);
return groupedAccounts;
}, {});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.