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)
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.
Its complaining that the item could be undefined. Just change tap to tap<number | undefined>
function tap<T>(array: T[], callback: (array: T[]) => T): T {
return callback(array);
}
const myResult = tap<number | undefined>([1, 2, 3, 4], (item) => {
if (item.length !== 0) {
return item.pop();
} else {
return 1;
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With