使用Type:Function与Type:any时出错



为了学习,我创建了一个简单的map2函数,该函数传递了一个增量函数。但是,我不能显式地将其作为Function传递(applyFun必须作为类型any传递(。

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);

游乐场链接

相关内容

最新更新