Home > Net >  Typescript cant determine type of callback function correctly
Typescript cant determine type of callback function correctly

Time:11-17

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)

CodePudding user response:

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.

CodePudding user response:

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

CodePudding user response:

I would guess your error is here

return item.pop()

item.pop() can potentially return 'undefined'. That is why you are returning 'number | undefined'.

I believe it could work like this

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()!
  }
  return 1
})

I simply added '!' at the end of pop() :-)

that is telleing typescript that it can safely trust your code and that you will indeed never return an undefined value. Since you have a condition checking the behaviour of the code, you can safely add the '!'.

I would not recommend adding this without a check, though.

Cheers!

  • Related