减少打字稿中的文字

时间:2020-07-23 12:09:22

标签: typescript types

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
}, [])

如何解决我遇到的此类错误?

3 个答案:

答案 0 :(得分:1)

假设p + geom_label( data=subset(plotdata, change != 0), aes(x=x, y=y, label=paste0(ifelse( subset(plotdata, change!=0)$change <0, '','+'), round(change, 2),'%')), color=ifelse(subset(plotdata, change!=0)$change <0, 'red','green3'), nudge_x = -0.3 ) columns的类型为rows,则可以指定作为number[]的第二个参数传递的空数组的类型,如下所示:

reduce

或者像这样将类型参数传递给const field = columns.reduce((array, y) => { rows.map(x => array.push({ x: x, y: y })) return array }, [] as Array<{ x: number, y: number }>)

reduce

答案 1 :(得分:0)

您用于reduce方法的初始化程序目前是一个空数组[]

将该初始值设置为正确的类型:

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)

或将该类型赋予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

答案 2 :(得分:0)

使用reduce的好方法是columns.reduce<Array<{ x: number, y: number }>>。但是,在这种情况下,我不会使用reduce,但如果支持ES2019,则将使用flatMap

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