為什么打字稿不能使用下面的代碼來減少?這里也有一個演示。
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
}, [])
uj5u.com熱心網友回復:
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);
uj5u.com熱心網友回復:
默認情況下,Typescript 中的空陣列是神經元 [] 型別,因此您必須明確指定型別
const x = temp.reduce((accum, o) => {
accum.push(o.stations)
return accum
}, [] as {id: string}[][])
uj5u.com熱心網友回復:
在 TS 中,空陣列默認為 type 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}[][])
演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/480276.html
標籤:javascript 打字稿
