繁体   English   中英

反应 typescript 错误 - 元素隐式具有任何类型,因为类型字符串的表达式不能用于索引类型 {}

[英]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.

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