Awaited能处理任意深度嵌套,因其是TypeScript内置递归工具类型,自动逐层解析Promise或Thenable的onfulfilled参数类型直至非Promise类型,对基础类型保持原样。

直接用 Awaited
为什么 Awaited 能处理任意嵌套
Awaited 是 TypeScript 内置的递归展开工具类型,定义在标准库 lib.es2022.d.ts 中。它不只是识别 Promise<u></u>,还会检测任意具备 then 方法的对象(即 Thenable),并逐层递归解析其 onfulfilled 参数所接收的值类型,直到抵达非 Promise 类型为止。
-
Awaited<promise>></promise>→string -
Awaited<promise>>></promise>→number -
Awaited<promise null>>>></promise>→boolean | null -
Awaited void) => void }>→Date
配合 ReturnType 提取异步函数返回值类型
实际项目中,你通常不直接操作 Promise 类型字面量,而是想拿到某个 async 函数 await 后的真实返回类型。这时组合 Awaited<returntype>></returntype> 是最自然的做法:
使用 Scrapfly SDK(scrapfly-sdk)在 TypeScript 或 JavaScript 中进行网页抓取,用于用户请求抓取 URL、绕过反爬虫防护、渲染页面等场景。
- 定义函数:
async function fetchUser(): Promise { ... } - 提取类型:
type User = Awaited<returntype fetchuser>>;</returntype> - 结果:
User就是{ id: number; name: string },完全不含 Promise
处理 API 响应这类常见嵌套结构
很多 HTTP 客户端(如 Axios)或自定义封装会返回 Promise<response>></response> 形式,其中 Response 是带 data 字段的容器类型。此时可结合索引访问与 Awaited:
type ApiResponse<t> = { code: number; data: T; message?: string };</t>async function apiCall(): Promise<apiresponse status:>> { ... }</apiresponse>type Result = Awaited<returntype apicall>>['data']; // { status: 'ok' }</returntype>
注意边界情况:null、undefined 和非 Thenable 类型
Awaited 对基础类型保持原样,不会做任何转换:
-
Awaited<string></string>→string -
Awaited<null></null>→null -
Awaited<undefined></undefined>→undefined -
Awaited<number></number>→number[]
这种设计保证了类型安全——只有真正可 await 的类型才会被展开,其余一律透传,避免误判和隐式转换。

















