¿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 }, [])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 worksAquí 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);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}[][])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}[][])