简体   繁体   中英

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:

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? I am completely new to 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

    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).

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[]> :

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;
}, {});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM