网站搜索

javascript - 对象数组使用 reduce 时 TypeScript 错误:不能赋值给类型为 'never' 的参数


为什么 TypeScript 不能使用下面的代码进行 reduce?这里也有一个演示。

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

const x = temp.reduce((accum, o) => { // temp.reduce<never[]>(...)
    accum.push(o.stations) // ! nothing is assignable to never

    return accum
}, []); // inferred as never[]

你需要传递泛型给 reduce,或者将 [] 强制类型转换:

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

在这里你会找到这两个解决方案。


但我可以问一下你为什么在这里还使用 reduce 吗?一个简单的 map 会更快、更简单……

const x = temp.map((o) => o.stations);

答案#2

在 Typescript 中,默认情况下空数组的类型是 never[],所以你必须明确指定类型

const x = temp.reduce((accum, o) => {
    accum.push(o.stations)
    return accum
}, [] as {id: string}[][])