用于promise.reject的TypeScript类型定义 [英] TypeScript type definition for promise.reject
问题描述
以下代码在返回类型方面是正确的,因为然后
始终返回promise数组。
The following code is correct in terms of the type that is returned, because then
always return the promise array.
Promise.resolve(['one', 'two'])
.then( arr =>
{
if( arr.indexOf('three') === -1 )
return Promise.reject( new Error('Where is three?') );
return Promise.resolve(arr);
})
.catch( err =>
{
console.log(err); // Error: where is three?
})
TypeScript抛出错误:
TypeScript throw error:
无法从用法中推断出类型参数 TResult的类型参数。考虑明确指定类型参数。
类型参数候选'void'不是有效的类型参数,因为它不是候选'string []'的超类型。
The type argument for type parameter 'TResult' cannot be inferred from the usage. Consider specifying the type arguments explicitly. Type argument candidate 'void' is not a valid type argument because it is not a supertype of candidate 'string[]'.
但是实际上,然后
永远不会返回 void
。
But in reality, then
never will return void
.
我可以显式指定类型。然后
I can explicitly specify type .then<Promise<any>>
, but it's more like a workaround, not the right solution.
如何正确书写?
推荐答案
您不应返回 Promise.resolve
和 Promise.reject
内的承诺链。 解决
应该由简单的返回驱动,而拒绝
应该由显式的抛出新的驱动。错误
。
You should not return Promise.resolve
and Promise.reject
inside a promise chain. The resolve
should be driven by simple return and reject
should be driven by an explicit throw new Error
.
Promise.resolve(['one', 'two'])
.then( arr =>
{
if( arr.indexOf('three') === -1 )
throw new Error('Where is three?');
return arr;
})
.catch( err =>
{
console.log(err); // Error: where is three?
})
更多
有关承诺链的更多信息 https://basarat.gitbooks.io/typescript/content/docs/promise.html
这篇关于用于promise.reject的TypeScript类型定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!