Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot invoke an expression whose type lacks a call signature for function returning resolved promise

I'm trying to call a function which returns a resolved promise using Promise.resolve based on some condition.

An over simplified version of the function is as follows:

  function fullFilledPromiseReturner(num: number) {
    if (num > 5) {
      return Promise.resolve(5);
    } else {
      return Promise.resolve();
    }
  }

  fullFilledPromiseReturner(4).then(data => {
    console.log(data);
  });

Now TypeScript is not letting it go through compiler and is throwing following error:

[ts] Cannot invoke an expression whose type lacks a call signature. Type '(<TResult1 = void, TResult2 = never>(onfulfilled?: ((value: void) => TResult1 | PromiseLike<TResu...' has no compatible call signatures.enter image description here

What am I doing wrong?

like image 531
pranavjindal999 Avatar asked Mar 16 '18 18:03

pranavjindal999


1 Answers

The problem is that your function returns Promise<void> | Promise<number> since you return different promise types on different branches. So then will also be a union type and you will not be able to invoke it as none of the signatures will be common.

The simplest solution would be to explicitly type the function to return a Promise of a union type instead of a union of Promises:

function fullFilledPromiseReturner(num: number): Promise<number | void> {
    if (num > 5) {
        return Promise.resolve(5);
    } else {
        return Promise.resolve();
    }
} 
fullFilledPromiseReturner(4).then(data => {
    console.log(data);
});
like image 182
Titian Cernicova-Dragomir Avatar answered Sep 30 '22 05:09

Titian Cernicova-Dragomir