'Array of object reduce typescript error: not assignable to parameter of type 'never'
Why can't typescript do reduce using below code? Here a demo as well.
const temp = [
{
"id": "1",
"stations": [{
id: 'abc'
}],
},
{
"id": "2",
"stations": [{
id: 'def'
}]
}
]
const x = temp.reduce((accum, o) => {
accum.push(o.stations) //what's wrong here?
return accum
}, [])
Solution 1:[1]
const x = temp.reduce((accum, o) => { // temp.reduce<never[]>(...)
accum.push(o.stations) // ! nothing is assignable to never
return accum
}, []); // inferred as never[]
You'll need to either pass the generic to reduce, or cast the []:
// EITHER one of these will work, choose which one you think "looks" better
const x = temp.reduce<
typeof temp[number]["stations"][] // here
>((accum, o) => { // temp.reduce<never[]>(...)
accum.push(o.stations) // ! nothing is assignable to never
return accum
}, [] as typeof temp[number]["stations"][]); // also works
Here you will find the two solutions.
But may I ask why you are even using reduce here? A simple map could work faster and simpler...
const x = temp.map((o) => o.stations);
Solution 2:[2]
By default empty arrays in Typescript are of type nerver[], So you have to explicitly specify the type
const x = temp.reduce((accum, o) => {
accum.push(o.stations)
return accum
}, [] as {id: string}[][])
Solution 3:[3]
In TS empty arrays are by default of type never[]. That is what throws the error. You need to properly type it.
Something as simple as this will do:
const x = temp.reduce((accum, o) => {
accum.push(o.stations) //what's wrong here?
return accum
}, [] as any[])
If you want to type it properly just initialize the array as such:
const x = temp.reduce((accum, o) => {
accum.push(o.stations) //what's wrong here?
return accum
}, [] as { id : string}[][])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | hittingonme |
| Solution 2 | JeannotMn |
| Solution 3 |
