-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 | }
4

1 Answer 1

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).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.