[英]react typescript error - element implicitly has an any type because expression of type string cant be used to index type {}
I am trying to group an array by x in my react project using typescript and getting the following error:我正在尝试使用 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
Can someone help me define this so it removes the typescript error?有人可以帮我定义它以消除 typescript 错误吗? I am completely new to React.
我是 React 的新手。
here is the location of the error这是错误的位置
const result = trades.reduce((groupedAccounts, trade) => {
const account = trade.pacct;
if (groupedAccounts[account] == null) groupedAccounts[account] = [];
groupedAccounts[account].push(trade);
return groupedAccounts;
}, {});
here is my export interface from another.ts这是我从 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;
}
I'm sure its a syntax issue I just don't understand.我确定这是我不明白的语法问题。
reduce
can take a generic to specify what the predicate returns (and the type of the initial value). reduce
可以采用泛型来指定谓词返回的内容(以及初始值的类型)。
Here it is inferred as {}
because of the initial value:由于初始值,此处将其推断为
{}
:
const result = trades.reduce((groupedAccounts, trade) => {
const account = trade.pacct;
if (groupedAccounts[account] == null) groupedAccounts[account] = [];
groupedAccounts[account].push(trade);
return groupedAccounts;
}, {});
You probably want it to be Record<string, TradeData[]>
:您可能希望它是
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.