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
}, [])
CodePudding user response:
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);
CodePudding user response:
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}[][])
CodePudding user response:
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}[][])