Rudenya
Rudenya

Reputation: 27

Type reduce in typescript

const field: Array<{x: number, y: number}> = columns.reduce((array, y) => {
    rows.map(x => array.push({x: x, y: y})) //Error:(20, 39) TS2322: Type 'number' is not                                    
                                            //assignable to type never
    return array
}, [])

How to solve this type error I'm having?

Upvotes: 0

Views: 241

Answers (3)

HTN
HTN

Reputation: 3604

The good way for using reduce is columns.reduce<Array<{ x: number, y: number }>>. However, I would not use reduce in this case, but flatMap if ES2019 is supported:

const field = columns.flatMap(y => rows.map(x => ({ x, y })));

Upvotes: 0

Luke Storry
Luke Storry

Reputation: 6752

Your initialiser for the reduce method is currently an empty array [].

Set that initial value to have the correct type:

type coordinatesType = Array<{ x: number, y: number }>

const field = columns.reduce((array, y) => {
  rows.forEach(x => array.push({ x: x, y: y }))
  return array
}, [] as coordinatesType)

Or give that type to the reduce

type coordinatesType = Array<{ x: number, y: number }>

const field = columns.reduce<coordinatesType>((array, y) => {
  rows.forEach(x => array.push({ x: x, y: y }))
  return array
}, [])

Playground

Upvotes: 0

Valentin
Valentin

Reputation: 11812

Assuming columns and rows have type number[], you can either specify the type of the empty array passed as second parameter of reduce like this:

const field = columns.reduce((array, y) => {
  rows.map(x => array.push({ x: x, y: y }))
  return array
}, [] as Array<{ x: number, y: number }>)

Or pass the type parameter to reduce like that:

const field = columns.reduce<Array<{ x: number, y: number }>>((array, y) => {
  rows.map(x => array.push({ x: x, y: y }))
  return array
}, [])

Upvotes: 1

Related Questions