无法使用' map'函数返回数组或数字的方法

时间:2018-06-05 08:30:47

标签: typescript typescript-typings typescript2.0

当我在下面运行此代码时出现错误:" [ts] 物业'地图'类型'数字|中不存在数[]&#39 ;.   物业'地图'类型''"

上不存在



const a = [
  1, 2, 3, 4, 5,
]

const testFunc : (data: number[], options?: string) => number[] | number = function (data: number[], options?: string) {
  if (options === 'array') return [1, 2, 3]
  return 1
}
const whichType = testFunc(a, 'array')
const double = whichType.map(item => item*2)



 当我将鼠标悬停在'哪个类型'它告诉我这是数字。但实际上不是数字 有谁知道为什么' whichType'不是数字[]'。

感谢。

1 个答案:

答案 0 :(得分:0)

whichTypenumber | number[]的联合类型。

您需要缩小它以使用它:

if (typeof whichType === 'number') {
    // It's a number
} else {
    // It's an array
    const double = whichType.map(item => item * 2);
}
相关问题