Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript cant determine type of callback function correctly

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)
like image 667
Alasgar Avatar asked Oct 27 '25 05:10

Alasgar


2 Answers

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.

like image 124
Erlind Bylykbashi Avatar answered Oct 29 '25 20:10

Erlind Bylykbashi


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;
  }
});
like image 22
Vayne Valerius Avatar answered Oct 29 '25 20:10

Vayne Valerius



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!