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

TypeScript中Promise块内函数返回类型的正确推断实现问题

解决方案

核心问题原因

  • 原函数没有对Promise的reject情况做捕获,无法达到替代try...catch的设计目标
  • 泛型没有约束入参为Promise类型,无法正确提取Promise resolve的返回值类型
  • 函数返回值默认被TypeScript推断为普通联合类型数组,而非固定位置类型的元组,无法关联每个位置的对应类型

修正后的代码实现

基础可用版本

能满足基本类型推断需求,返回值第一位为Promise结果或null,第二位为是否出错的标记:

async function solve<T>(promise: Promise<T>): Promise<[T | null, boolean]> {
  try {
    const res = await promise;
    return [res, false];
  } catch (e) {
    return [null, true];
  }
}

严格类型窄化版本

使用可辨识联合定义返回类型,判断出错标记后TypeScript会自动窄化结果类型,不需要额外做非空判断:

async function solve<T>(promise: Promise<T>): Promise<[T, false] | [null, true]> {
  try {
    const res = await promise;
    return [res, false];
  } catch (e) {
    return [null, true];
  }
}

调用示例

(async ()=>{
  const [a, isError] = await solve(new Promise(resolve => {
    setTimeout(()=>{
      resolve({
        n: 1
      })
    }, 2000)
  }));

  // 先判断是否出错,TS会自动窄化a的类型
  if (isError) {
    console.log('处理异常逻辑')
    return
  }
  // 此处a会被自动推断为{ n: number }类型,有完整智能提示,无类型错误
  console.log(a.n)
})();

如果不需要做错误分支处理,也可以直接用可选链访问属性console.log(a?.n),同样不会触发类型错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 16:45:04