skip to content

TypeScript
TS 工具类型 - Awaited

本文将介绍 Awaited<T> 的用法和原理,并通过示例代码演示其实际应用。

是什么

在 TypeScript 中,Awaited<T> 是一个内置的工具类型,用于获取 Promise 返回值的类型。它接受一个类型参数 T,通常是一个 Promise 类型,然后返回 Promise 的结果类型。

怎么用

下面是一个简单的示例,演示了如何使用 Awaited<T>

// 定义一个返回 Promise 的函数
function delay(ms: number): Promise<string> {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('done')
    }, ms)
  })
}

// 使用 Awaited 获取 Promise 返回类型
type Result = Awaited<ReturnType<typeof delay>>

async function asyncFunction() {
  const result: Result = await delay(1000)
  console.log(result) // 输出: done
}

asyncFunction()

在这个示例中,Awaited<ReturnType<typeof delay>> 等同于 Awaited<Promise<string>>,最终将 result 推断为 string 类型,输出 done

看源码

/**
 * Recursively unwraps the "awaited type" of a type. Non-promise "thenables" should resolve to `never`. This emulates the behavior of `await`.
 */
type Awaited<T> = T extends null | undefined
  ? T // special case for `null | undefined` when not in `--strictNullChecks` mode
  : T extends object & { then(onfulfilled: infer F, ...args: infer _): any } // `await` only unwraps object types with a callable `then`. Non-object types are not unwrapped
  ? F extends (value: infer V, ...args: infer _) => any // if the argument to `then` is callable, extracts the first argument
    ? Awaited<V> // recursively unwrap the value
    : never // the argument to `then` was not callable
  : T // non-object or non-thenable

Source Code

总结

通过 Awaited<T>,我们可以轻松地获取 Promise 返回值的类型,使代码更加类型安全。这个工具类型在处理异步操作时特别有用,能够帮助我们更好地理解和利用 TypeScript 的类型系统。