Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

253
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda