#Type 'void' is not assignable to type '(string | number)[]'

13 messages · Page 1 of 1 (latest)

sour steppe
#

I am getting a void error for varialbe "postData".
Can anyone, see what the issue is. I worked on it several hours but can not find any

const postData: (string | number | { target_id: number; })[] = selectedRows.forEach((row: any) => {
postData.push({ target_id:
row.original.target_id });
});
amber temple
sour steppe
#

I also, tried with map, but with no help, got same or another error. But what if I want to use forEach?

drowsy wrenBOT
#
krofdrakula#6425

Preview:ts ... const postData: ( | string | number | {target_id: number} )[] = selectedRows.map((row: any) => { return { target_id: row.original.target_id, } })

amber temple
#

👆 that's the map() version

sour steppe
#

Perfect, I have to play with it a bit in order to understand. But thanks for your help :))

drowsy wrenBOT
#
krofdrakula#6425

Preview:```ts
...
const postData: (
| string
| number
| {target_id: number}
)[] = []

selectedRows.forEach((row: any) => {
postData.push({
target_id: row.original.target_id,
})
})```

amber temple
#

and that's the forEach version. the difference is that map also creates the array for you and populates it with elements that your function returns. in the second case, you have to create your own array and push into it. that's usually preferable if the two arrays do not match elements 1:1 (you can push more or less items than to the target array relative to the source array)

sour steppe
#

I noticed that we are not pusing anything into the array when using map?

amber temple
#

best way to imagine forEach is like a for...of loop, you have to do everything manually

#

yes. map() creates the array for you and fills it with values returned by the function you give it. read the MDN docs on both for an explanation of each 🙂

ashen pulsar
#

Hi @sour steppe and krofdrakula, I’m Alexander Lill (a real person), a researcher at the University of Zurich. I’m trying to help people receive answers faster on Discord. If you are not ok with giving me some feedback, click the 🚪 symbol, and I will delete this message and apologize for the inconvenience.

#

Would any of the provided links have helped to answer the OPs question? Please click the number-emoji for each link that would have been helpful, and on the ❌ if none of the links would have been helpful to answer the OPs question.

1️⃣ Type 'void[]' is not assignable to type 'Foo[]'
https://stackoverflow.com/questions/62780947

2️⃣ TypeScript error: Void is not assignable to parameter type
https://stackoverflow.com/questions/53328477

3️⃣ Why is TypeScript throwing the void is not assignable error?
https://stackoverflow.com/questions/65099107

Let me know if you have any questions! More info: #1063200184315674706