Typescript 无法使用';地图';函数返回数组或数字时的方法
当我在下面运行此代码时,它出现错误:“[ts] 类型“number | number[]”上不存在属性“map”。 类型“number”上不存在属性“map”Typescript 无法使用';地图';函数返回数组或数字时的方法,typescript,typescript-typings,typescript2.0,Typescript,Typescript Typings,Typescript2.0,当我在下面运行此代码时,它出现错误:“[ts] 类型“number | number[]”上不存在属性“map”。 类型“number”上不存在属性“map” const a=[ 1, 2, 3, 4, 5, ] const testFunc:(数据:number[],选项?:字符串)=>number[]| number=函数(数据:number[],选项?:字符串){ if(options=='array')返回[1,2,3] 返回1 } 常量whichType=testFunc(一个“数组
const a=[
1, 2, 3, 4, 5,
]
const testFunc:(数据:number[],选项?:字符串)=>number[]| number=函数(数据:number[],选项?:字符串){
if(options=='array')返回[1,2,3]
返回1
}
常量whichType=testFunc(一个“数组”)
const double=whichType.map(item=>item*2)
whichType
是number | number[]的联合类型
您需要缩小范围才能使用它:
if (typeof whichType === 'number') {
// It's a number
} else {
// It's an array
const double = whichType.map(item => item * 2);
}
谢谢你救了我一天