首页 > 解决方案 > 错误使用类型:函数与类型:任何

问题描述

出于学习目的,我创建了一个简单的 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 的情况下在这里更明确?

标签: typescriptdictionarysyntax

解决方案


您需要更具体地使用函数签名。

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

游乐场链接


推荐阅读