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

做~自己de王妃 提交于 2019-12-10 05:56:37

问题


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.

What am I doing wrong?


回答1:


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 Promisses:

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


来源:https://stackoverflow.com/questions/49327264/cannot-invoke-an-expression-whose-type-lacks-a-call-signature-for-function-retur

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!