LoginSignup
4
0

More than 3 years have passed since last update.

TSでArray.reduce使ったら第一引数のaccumulatorがnever型になって混乱した話

Last updated at Posted at 2020-09-07

Array.reduceが一度も回らないとcallbackが無いのでaccumulatorはneverになる

配列の型に[]の空配列を想定していると一度も回らないのでaccumulatorの戻り値無しでnever型になる。
空が想定される場合はそもそも回す処理まで到達出来ないようにしてあげよう。


// const orderArray: string[]|[] = this.orderArray
// ↓
const orderArray: string[] = this.orderArray

arrFunc () {
  return orderArray.reduce((accumulator, id) => {
    const item: ItemDocument|undefined = items.find(item => item.id === id)
    if (item) { accumulator.push(item) }
      return accumulator
    }, [])
}

対策

  1. 型の[]がArray系関数に到達しない処理にする
  2. Arrayを型キャストする
    1. https://stackoverflow.com/questions/54117100/why-does-typescript-infer-the-never-type-when-reducing-an-array-with-concat
const orderArray = this.orderArray as string[]

arrFunc () {
  return orderArray.reduce((accumulator, id) => {
    const item: ItemDocument|undefined = items.find(item => item.id === id)
    if (item) { accumulator.push(item) }
      return accumulator
    }, [])
}
4
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
0