Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

256
Views
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
}, [])

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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);
about 4 years ago · Juan Pablo Isaza Report

0

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}[][])

Demo

about 4 years ago · Juan Pablo Isaza Report

0

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}[][])
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!