簡體   English   中英

對象數組減少打字稿錯誤:不可分配給“從不”類型的參數

[英]Array of object reduce typescript error: not assignable to parameter of type 'never'

為什么打字稿不能使用下面的代碼來減少? 這里也有一個演示

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

您需要將泛型傳遞給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 嗎? 一張簡單的地圖可以更快更簡單地工作......

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

在 TS 中,空數組默認為never[]類型。 這就是引發錯誤的原因。 您需要正確鍵入它。

像這樣簡單的事情就可以了:

const x = temp.reduce((accum, o) => {
    accum.push(o.stations) //what's wrong here?

    return accum
}, [] as any[])

如果要正確鍵入它,只需將數組初始化為:

const x = temp.reduce((accum, o) => {
    accum.push(o.stations) //what's wrong here?

    return accum
}, [] as { id : string}[][])

演示

默認情況下,Typescript 中的空數組是神經元 [] 類型,因此您必須明確指定類型

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM