打字稿承诺通用类型 [英] Typescript promise generic type
本文介绍了打字稿承诺通用类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个示例Promise函数,如下所示.成功时,我返回number
,如果失败,则返回string
.编译器抱怨为promise指定某种通用类型.在这种情况下,我必须指定哪种类型?我必须指定Promise<number>
还是Promise<number | string>
吗?
I've a sample Promise function like below. On success I return a number
and on false I return string
. The compiler is complaining to specify some kind of generic type to the promise. In this case what type I've to specify? Do I've to specify like Promise<number>
or Promise<number | string>
?
function test(arg: string): Promise {
return new Promise((resolve, reject) => {
if (arg === "a") {
resolve(1);
} else {
reject("1");
}
});
}
推荐答案
Promise的通用类型应对应于该函数的非错误返回类型.该错误隐式为any
类型,并且未在Promise泛型类型中指定.
The generic type of the Promise should correspond to the non-error return-type of the function. The error is implicitly of type any
and is not specified in the Promise generic type.
例如:
function test(arg: string): Promise<number> {
return new Promise<number>((resolve, reject) => {
if (arg === "a") {
resolve(1);
} else {
reject("1");
}
});
}
这篇关于打字稿承诺通用类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文