typescript - TypeScript 中的可等待类型
问题描述
我在 JavaScript 中经常使用 async / await。现在我正在逐渐将我的代码库的某些部分转换为 TypeScript。
在某些情况下,我的函数接受将被调用和等待的函数。这意味着它可能会返回一个承诺,只是一个同步值。我已经Awaitable
为此定义了类型。
type Awaitable<T> = T | Promise<T>;
async function increment(getNumber: () => Awaitable<number>): Promise<number> {
const num = await getNumber();
return num + 1;
}
可以这样调用:
// logs 43
increment(() => 42).then(result => {console.log(result)})
// logs 43
increment(() => Promise.resolve(42)).then(result => {console.log(result)})
这行得通。但是,必须为Awaitable
我所有使用 async/await 和 TypeScript 的项目指定是很烦人的。
我真的不敢相信这种类型不是内置的,但我找不到。TypeScript 是否有内置的可等待类型?
解决方案
我相信这个问题的答案是:不,没有内置类型。
在lib.es5.d.ts
和lib.es2015.promise.d.ts
中,它们用于您认为有意义T | PromiseLike<T>
的各个地方,例如:Awaitable<T>
/**
* Represents the completion of an asynchronous operation
*/
interface Promise<T> {
/**
* Attaches callbacks for the resolution and/or rejection of the Promise.
* @param onfulfilled The callback to execute when the Promise is resolved.
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of which ever callback is executed.
*/
then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): Promise<TResult1 | TResult2>;
/**
* Attaches a callback for only the rejection of the Promise.
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of the callback.
*/
catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<T | TResult>;
}
在他们定义和的地方没有什么像你Awaitable
的。lib.es5.d.ts
PromiseLike
Promise
我想如果他们定义了一个,他们会在这些定义中使用它。
旁注:基于这些定义,使用PromiseLike
而不是Promise
在您的Awaitable
:
type Awaitable<T> = T | PromiseLike<T>;
推荐阅读
- javascript - 如何获得一致的数字排序结果?
- ruby-on-rails - Rspec:如何在失败的示例中访问当前种子编号
- excel - 如果单元格包含数据,则将数据向下偏移
- nativescript - 是否可以在 nativescript 中为进度元素添加最小限制
- javascript - 将 NODE_ENV 传递给 Windows 10 的 npm 脚本
- swift - 为我们的 Swift 包运行 SwiftLint 的简单方法
- c++ - 如何将 CSV 文件集成到 OMNeT++ 最新版本中?
- ios - 带有故事板 segues 的上下文菜单预览提供程序
- reactjs - 如何将 iFrame 导出为 PDF
- spring-boot - 在 Spring Boot 中发送有关错误发生的电子邮件