Typescript 使用Type:Function与Type:any时出错
出于学习的目的,我创建了一个简单的map2函数,并将其传递给增量函数。但是,我不能显式地将其作为函数传递(applyFun必须作为any类型传递) 我有一个问题,为什么从以下位置更改后:Typescript 使用Type:Function与Type:any时出错,typescript,dictionary,syntax,Typescript,Dictionary,Syntax,出于学习的目的,我创建了一个简单的map2函数,并将其传递给增量函数。但是,我不能显式地将其作为函数传递(applyFun必须作为any类型传递) 我有一个问题,为什么从以下位置更改后: function map2(arr: number[], applyFun: any): number[] 致: 导致错误: error TS2345: Argument of type 'Function' is not assignable to parameter of type '(value: nu
function map2(arr: number[], applyFun: any): 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);
后续问题:为什么我不能在这行中添加{}个数字,使其看起来像这样:
函数map2(arr:number[],applyFun:(val:number)=>{number}):number[]
?@MM。哪个号码?对不起,这个问题我不清楚。在你回答的第5行,你添加了“applyFun:(val:number)=>number”作为map2函数的第二个参数。为什么写“applyFun:(val:number)=>{number}”不正确?我想我回答了我的问题:如果你的函数在一个块中,你还必须使用显式的返回语句:
@MM.`(val:number)=>number`是一个类型,它是一个函数签名,=>
之后的部分是本例中的返回类型number
<代码>{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.
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);