首页 > 解决方案 > 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 是否有内置的可等待类型?

标签: typescriptasync-await

解决方案


我相信这个问题的答案是:不,没有内置类型。

lib.es5.d.tslib.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.tsPromiseLikePromise

我想如果他们定义了一个,他们会在这些定义中使用它。

旁注:基于这些定义,使用PromiseLike而不是Promise在您的Awaitable:

type Awaitable<T> = T | PromiseLike<T>;

推荐阅读