typescript 打字稿承诺泛型类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41078809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Typescript promise generic type
提问by VJAI
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>
?
我有一个像下面这样的示例 Promise 函数。成功时返回 a number
,失败时返回string
。编译器抱怨为承诺指定某种泛型类型。在这种情况下,我必须指定什么类型?我必须指定 likePromise<number>
或Promise<number | string>
?
function test(arg: string): Promise {
return new Promise((resolve, reject) => {
if (arg === "a") {
resolve(1);
} else {
reject("1");
}
});
}
回答by Dave Templin
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.
Promise 的泛型类型应该对应于函数的非错误返回类型。该错误属于隐式类型any
,未在 Promise 泛型类型中指定。
So for example:
例如:
function test(arg: string): Promise<number> {
return new Promise<number>((resolve, reject) => {
if (arg === "a") {
resolve(1);
} else {
reject("1");
}
});
}