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

254
Views
Matriz de objeto reduce el error de mecanografiado: no asignable al parámetro de tipo 'nunca'

¿Por qué el mecanografiado no puede reducir el uso del siguiente código? Aquí una demostración también.

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

Deberá pasar el genérico para reduce o lanzar el [] :

 // 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

Aquí encontrarás las dos soluciones.


Pero, ¿puedo preguntar por qué estás usando reduce aquí? Un mapa simple podría funcionar más rápido y más simple...

 const x = temp.map((o) => o.stations);
about 4 years ago · Juan Pablo Isaza Report

0

En TS, las matrices vacías son por defecto de tipo never[] . Eso es lo que arroja el error. Tienes que escribirlo correctamente.

Algo tan simple como esto hará:

 const x = temp.reduce((accum, o) => { accum.push(o.stations) //what's wrong here? return accum }, [] as any[])

Si desea escribirlo correctamente, simplemente inicialice la matriz como tal:

 const x = temp.reduce((accum, o) => { accum.push(o.stations) //what's wrong here? return accum }, [] as { id : string}[][])

Manifestación

about 4 years ago · Juan Pablo Isaza Report

0

Por defecto, las matrices vacías en TypeScript son de tipo nervio [], por lo que debe especificar explícitamente el tipo

 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!