2

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

1
  • 1
    You've given reduce [] as the starting value. [] is always inferred as never[]. Commented May 23, 2022 at 13:43

3 Answers 3

3
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);
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

-1

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

1 Comment

Please don't suggest using any :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.