gpt4 book ai didi

promise.reject 的 TypeScript 类型定义

转载 作者:搜寻专家 更新时间:2023-10-30 20:33:10 27 4
gpt4 key购买 nike

以下代码就返回的类型而言是正确的,因为 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 抛出错误:

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

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

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

这个怎么写对?

最佳答案

你不应该返回 Promise.resolvePromise.reject inside promise 链。 resolve 应该由简单的 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?
})

更多

关于 promise 链的更多信息 https://basarat.gitbooks.io/typescript/content/docs/promise.html

关于promise.reject 的 TypeScript 类型定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39381940/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com