You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript:如何从Promise参数推断通用Awaited类型?

解决TypeScript中CacheBuilder泛型推断返回Awaited类型的问题

问题分析

你当前的CacheBuilder泛型直接绑定到getValue的原始返回值类型,导致当getValue返回Promise<string>时,泛型参数会被推断为Promise<string>,最终得到Cache<Promise<string>>。而你需要的是将getValue返回值做Awaited解析后的类型,也就是Cache<string>。

解决方案

调整泛型参数的绑定逻辑,让泛型参数代表最终解析后的值类型,而非getValue的直接返回值:

// 重新定义GetValue,基于最终解析后的目标类型U
type GetValue<U> = (() => U) | (() => Promise<U>)

// 调整CacheBuilder的泛型,返回解析后的类型对应的Cache实例
type CacheBuilder = <U>(getValue: GetValue<U>, options?: BuildCacheOptions<U>) => Cache<U>

验证示例

用你提供的代码测试,现在类型推断会符合预期:

import { buildCache } from './cache'

const getMyVal = () => Promise.resolve('foo')

// 此时cache会被正确推断为Cache<string>
const cache = buildCache(getMyVal)

原理说明

  • 现在泛型参数U代表的是getValue返回值经过Awaited处理后的最终类型,TypeScript会自动完成推断:
    • 如果getValue返回同步值(比如string),U直接对应这个同步值类型;
    • 如果getValue返回Promise<string>,U会被自动解析为string(因为Awaited<Promise<string>>的结果就是string)。
  • 注意同步调整BuildCacheOptions的泛型参数为U,确保整个类型体系的一致性。

内容的提问来源于stack exchange,提问作者Cyril CHAPON

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 19:06:25