无法调用类型缺少调用签名的表达式以返回已解决的函数 [英] Cannot invoke an expression whose type lacks a call signature for function returning resolved promise
问题描述
我正在尝试调用一个函数,该函数根据某些条件使用 Promise.resolve
返回已解决的承诺。
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);
});
现在TypeScript不允许它通过编译器并抛出以下错误:
Now TypeScript is not letting it go through compiler and is throwing following error:
[ts]无法调用类型缺少调用签名的表达式。类型'(< TResult1 = void,TResult2 = never>(onfulfilled ?:((value:void)=> TResult1 | PromiseLike< TResu ...')没有兼容的呼叫签名。
我在做什么错了?
推荐答案
问题在于您的函数返回 Promise< void> | Promise< number>
,因为您在不同的分支上返回了不同的Promise类型。 c>然后还将是联合类型,您将无法调用它,因为所有签名都不是常见的。
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.
最简单的解决方案是显式键入该函数以返回联合类型的 Promise
而不是 Promisses
的联合:
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);
});
这篇关于无法调用类型缺少调用签名的表达式以返回已解决的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!