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

TypeScript中async函数ReturnType类型赋值报错问题求助

TypeScript async函数返回值类型标注问题解答

你遇到的问题核心是:async函数的返回值本身就是被Promise包裹的类型,ReturnType<typeof foo>获取到的是这个Promise类型(也就是Promise<string>),但await foo()会把Promise解包,得到的是内部的string值,两者类型自然不匹配。

解决方法

要获取async函数返回值的实际类型(即Promise内部的类型),需要用TypeScript提供的Awaited工具类型来解包Promise:

async function main() {
  const foo = async () => {
    return "foo";
  };

  // 用Awaited解包Promise,得到实际的string类型
  let fooResult: Awaited<ReturnType<typeof foo>>;

  fooResult = await foo(); // 类型匹配,编译通过
}

main();

补充说明

Awaited是TypeScript 4.5版本之后新增的工具类型,它能递归处理嵌套的Promise(比如Promise<Promise<string>>也能正确解包成string),比手动写string更灵活,尤其当你不确定async函数返回值具体类型时,用这个方法能自动推导正确的类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 15:01:00