问题
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