typescript - 错误使用类型:函数与类型:任何
问题描述
出于学习目的,我创建了一个简单的 map2 函数,它传递了一个增量函数。但是,我不能明确地将它作为函数传递(applyFun 必须作为任何类型传递)。
function increment(val:number):number {
return ++val;
}
function map2(arr: number[], applyFun: any): number[] {
const temp: number[] = arr.map(applyFun);
return temp;
}
let testArray = [1,2,3];
testArray= map2(testArray,increment);
console.log(testArray);
我有一个问题,为什么改变后:
function map2(arr: number[], applyFun: any): number[]
至:
function map2(arr: number[], applyFun: Function): number[]
导致错误:
error TS2345: Argument of type 'Function' is not assignable to parameter of type '(value: number, index: number, array: number[]) => number'.
Type 'Function' provides no match for the signature '(value: number, index: number, array: number[]): number'.
9 const temp: number[] = arr.map(applyFun);
~~~~~~~~
Found 1 error.
我问的是一个一般性问题,我如何在不使用 :any 的情况下在这里更明确?
解决方案
您需要更具体地使用函数签名。
function increment(val:number):number {
return ++val;
}
function map2(arr: number[], applyFun: (val: number) => number): number[] {
const temp: number[] = arr.map(applyFun);
return temp;
}
let testArray = [1,2,3];
testArray= map2(testArray,increment);
console.log(testArray);
推荐阅读
- reactjs - React 项目运行 React 本机启动命令
- angular - 如何以角度从对话框组件传递和访问数据?
- python - 如何计算两个坐标系之间的平均/最佳旋转?
- javascript - CKEditor 5 版本 29(在线生成器) - 无法加载自定义构建
- tableau-desktop - 如何将子类别值转换为表格文本表中的列
- php - 刷新后会话数据不可用
- python - 在桌面应用程序上显示假名
- java - Groovy 自定义 MetaClassImpl 导致“找不到匹配的构造函数”
- python - 为什么 X 和 Y 的变化对 w4 和 w2 没有影响?
- javascript - 通过 id 从 prisma 客户端获取最新数据