【问题标题】:TypeScript: Why Object.fromEntries does not accept array of tuple? [duplicate]TypeScript:为什么 Object.fromEntries 不接受元组数组? [复制]
【发布时间】:2021-11-05 12:42:21
【问题描述】:
  1. 我创建了一个元组数组
  2. 然后用Object.fromEntries将其转换为对象
  3. 然后我将分配给<{ [formFieldId: string]: number }> 类型。

这里有什么问题?

const [itemsWithSelection, setItemsWithSelection] = useState<{ [formFieldId: string]: number }>(itemsWithSelection2)
if (!itemsWithSelection2) {
  let aa = Object.keys(invoiceItems).forEach((key) =>
    [key, 1]
  )
  setItemsWithSelection(Object.fromEntries(aa))
}

得到了这个错误:

./components/product/InvoiceItemsToDeliver.tsx:30:44
Type error: No overload matches this call.
  Overload 1 of 2, '(entries: Iterable<readonly [PropertyKey, number]>): { [k: string]: number; }', gave the following error.
    Argument of type 'void' is not assignable to parameter of type 'Iterable<readonly [PropertyKey, number]>'.
  Overload 2 of 2, '(entries: Iterable<readonly any[]>): any', gave the following error.
    Argument of type 'void' is not assignable to parameter of type 'Iterable<readonly any[]>'.

  28 |     [key, 1]
  29 |   )
> 30 |   setItemsWithSelection(Object.fromEntries(aa))
     |                                            ^
  31 | }

【问题讨论】:

标签: typescript


【解决方案1】:

您可能想在此处使用.map 而不是.forEach

const [itemsWithSelection, setItemsWithSelection] = useState<{ [formFieldId: string]: number }>(itemsWithSelection2)
if (!itemsWithSelection2) {
  let aa = Object.keys(invoiceItems).map((key) =>
    [key, 1]
  )
  setItemsWithSelection(Object.fromEntries(aa))
}

第一个基于回调的内容生成一个新数组(或者在 Swift 中通常称为“闭包”);而第二个主要用于副作用,并且总是返回 undefined(一个类似于 Swift 的 Void 的值)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-07
    • 2015-12-26
    • 2017-10-21
    • 2020-12-25
    • 1970-01-01
    • 2011-12-28
    • 2015-07-06
    相关资源
    最近更新 更多