我在 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 有内置的可等待类型吗?
我相信这个问题的答案是:不,没有内置类型。
In lib.es5.d.ts https://github.com/microsoft/TypeScript/blob/eb2297df022f6b1f284aff96e93c06097bb01ea5/lib/lib.es5.d.ts and lib.es2015.promise.d.ts https://github.com/microsoft/TypeScript/blob/eb2297df022f6b1f284aff96e93c06097bb01ea5/lib/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
in lib.es5.d.ts
他们定义的地方PromiseLike
and Promise
.
我认为如果他们定义了一个,他们会在这些定义中使用它。
旁注:根据这些定义,使用可能是有意义的PromiseLike
而不是Promise
在你的Awaitable
:
type Awaitable<T> = T | PromiseLike<T>;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)