Home > Net >  react typescript error - element implicitly has an any type because expression of type string cant b
react typescript error - element implicitly has an any type because expression of type string cant b

Time:04-07

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.

CodePudding user response:

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