Issue
After running this typescript code it gives me an error on the item parameter of a callback function.Can't find what the problem is
function tap<T>(array:T[],callback:(array:T[])=> T ):T{
return callback(array)
}
const myResult = tap<number>([1,2,3,4],(item)=>{
if(item.length !==0 ){
return item.pop()
}else{
return 1
}
})
error output
Argument of type '(item: number[]) => (() => number | undefined) | 10' is not assignable to parameter of type '(array: number[]) => number'.
Type '(() => number | undefined) | 10' is not assignable to type 'number'.
Type '() => number | undefined' is not assignable to type 'number'.ts(2345)
Solution
item.pop()
might return undefined. You can modify the callback function to
const myResult = tap<number>([1,2,3,4], (item) => {
return item.pop() ?? 1;
})
If the array was empty and pop()
returned undefined
the callback function will return 1.
Answered By - Erlind Bylykbashi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.