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

日光

我正在尝试使用打字稿在我的反应项目中按 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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

错误 TS7053:元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引“模块类型”

打字稿“元素隐式具有'任何'类型,因为'Rank'类型的表达式不能用于索引类型'IPowerCards'”

Typescript错误:元素隐式具有“ any”类型,因为类型“ string”的表达式不能用于索引类型

打字稿错误:“字符串”类型的表达式不能用于索引类型

map()中的Typescript错误:元素隐式具有“ any”类型,因为类型“ string”的表达式不能用于索引类型

元素隐式地具有“ any”类型,因为在打字稿中将字符串转换为enum时,索引表达式不是enum的“ number”类型

打字稿 - “字符串”类型的表达式不能用于索引类型

元素隐式具有“任何”类型,因为索引表达式不是“数字”类型的打字稿 - 从数组中获取单个键

元素隐式具有“任意”类型,因为类型“字符串”的表达式不能用于索引类型A

元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引“类型”类型

元素隐式具有“任意”类型,因为类型“字符串”的表达式不能用于索引

元素隐式地具有“ any”类型,因为索引表达式不是“ number”类型。-索引签名错误

TypeScript:元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型

Angular - 元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型

如何修复元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型?

TS7053:元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引“User_Economy”类型

错误:参数“e”隐式具有“任何”类型。TS7006 - 反应打字稿

元素隐式具有 'any' 类型,因为类型 'string' 的表达式不能用于索引类型 {"1" : { "key": string}; "2" : { "key": 字符串};}

打字稿中的原型:元素隐式具有“任何”类型,因为类型“_BaseOption”没有索引签名

当 noImplicitAny 打开时,打字稿抛出 TS7017 错误并带有消息:元素隐式具有“任何”类型,因为类型“{}”没有索引签名

模板文字键具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型

Object.keys迭代导致Typescript错误“元素隐式具有'any'类型,因为索引表达式不是'number'类型”

反应路由器+打字稿类型错误

用 react-spring 反应打字稿类型错误

元素隐式具有“any”类型,因为“string”类型的表达式不能用于索引“Breakpoints”类型

元素隐式地具有“ any”类型,因为类型“ any”的表达式不能用于索引类型

元素隐式地具有“ any”类型,因为类型“ string”的表达式不能用于索引类型

元素隐式具有“any”类型,因为“string”类型的表达式不能用于索引“Palette”类型

元素隐式具有 'any' 类型,因为类型 'string' 的表达式不能用于索引类型 '{ AT: number; 是:数字,...}`