-2
  1. I make a array of tuple
  2. Then convert it to object with Object.fromEntries
  3. Then I would assign to a <{ [formFieldId: string]: number }> type.

What is wrong here?

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

and got this error:

./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 | }
János
  • 32,867
  • 38
  • 193
  • 353
  • `forEach` doesn't return anything - `aa` is always `undefined`. – VLAZ Sep 08 '21 at 18:44
  • I tried `{return [key, 1]}` also, same result – János Sep 08 '21 at 18:45
  • Because `.forEach()` doesn't return anything... – VLAZ Sep 08 '21 at 18:46
  • 2
    Also relevant: [Function with forEach returns undefined even with return statement](https://stackoverflow.com/q/16392445) | [JavaScript: Difference between .forEach() and .map()](https://stackoverflow.com/q/34426458) | [What does `return` keyword mean inside `forEach` function?](https://stackoverflow.com/q/34653612) – VLAZ Sep 08 '21 at 18:49

1 Answers1

0

You likely want to use .map here instead of .forEach:

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

The first produces a new array based on the contents of the callback (or what is often called "closure" in Swift); while the second is used primarily for side effects, and always returns undefined (a value similar to Swift's Void).

Parzh from Ukraine
  • 7,999
  • 3
  • 34
  • 65