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?
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 Promise
s:
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With