promise.reject 的 TypeScript 类型定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39381940/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:49:41  来源:igfitidea点击:

TypeScript type definition for promise.reject

typescriptes6-promise

提问by ktretyak

The following code is correct in terms of the type that is returned, because thenalways return the promise array.

以下代码在返回的类型方面是正确的,因为then始终返回 promise 数组。

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 throw error:

打字稿抛出错误:

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[]'.

无法从用法推断出类型参数“TResult”的类型参数。考虑明确指定类型参数。类型参数候选 'void' 不是有效的类型参数,因为它不是候选 'string[]' 的超类型。

But in reality, thennever will return void.

但实际上,then永远不会回来void

I can explicitly specify type .then<Promise<any>>, but it's more like a workaround, not the right solution.

我可以明确指定 type .then<Promise<any>>,但这更像是一种解决方法,而不是正确的解决方案。

How to write this right?

这个怎么写才对?

采纳答案by basarat

You should not return Promise.resolveand Promise.rejectinsidea promise chain. The resolveshould be driven by simple return and rejectshould be driven by an explicit throw new Error.

您不应该返回Promise.resolvePromise.reject承诺链中。Theresolve应该由简单的 return 驱动,并且reject应该由一个显式的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?
})

More

更多的

More on promise chaining https://basarat.gitbooks.io/typescript/content/docs/promise.html

更多关于承诺链https://basarat.gitbooks.io/typescript/content/docs/promise.html

回答by Ben Southgate

Typescript is complaining about the difference in return type between your Promise.rejectreturn value (Promise<void>) and your Promise.resolvevalue (Promise<string[]>).

Typescript 抱怨Promise.reject返回值 ( Promise<void>) 和Promise.resolve值 ( Promise<string[]>)之间的返回类型不同。

Casting your thencall as .then<Promise<void | string[]>>will let the compiler know of the union return type.

将您的then调用转换为 as.then<Promise<void | string[]>>将使编译器知道联合返回类型。

as @basarat notes, you should just throw an error instead of using Promise.reject (which will be passed to whatever catch handler is provided).

正如@basarat 所指出的,您应该只抛出一个错误而不是使用 Promise.reject (它将被传递给提供的任何捕获处理程序)。