我正在尝试使用打字稿在我的反应项目中按 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
有人可以帮我定义它以消除打字稿错误吗?我对 React 完全陌生。
这是错误的位置
const result = trades.reduce((groupedAccounts, trade) => {
const account = trade.pacct;
if (groupedAccounts[account] == null) groupedAccounts[account] = [];
groupedAccounts[account].push(trade);
return groupedAccounts;
}, {});
这是我从另一个 .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;
}, {});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句