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

为什么TypeScript无法推断该示例中Promise resolve后的变量类型?

类型推断为any的原因
  • 数组默认推断规则:TypeScript 对未显式标注类型的数组字面量,默认会推断为可变长度的联合类型数组,而非固定长度、位置类型固定的元组。你代码中promise.then(data => [data, null])的返回值会被推断为(TResult | null)[];catch(err => [null, err])的返回值默认推断为(null | any)[](catch 语句的错误参数默认类型为any,除非开启useUnknownInCatchVariables编译选项)。
  • 返回值联合推导规则:destructPromise没有显式标注返回值类型,TS 会自动合并 then 和 catch 两个分支的返回类型,最终合并结果为any[]。因此await destructPromise(test())的整体返回值是any[],解构得到的a、b自然都是any类型。
修复方案

你可以通过显式标注返回值为元组类型解决问题:

const destructPromise = <TResult>(promise: Promise<TResult>): Promise<[TResult | null, Error | null]> => {
  return promise
    .then(data => [data, null])
    .catch(err => [null, err as Error]);
};

也可以通过as const断言让 TS 自动将数组字面量识别为元组,省略手动标注返回值的步骤:

const destructPromise = <TResult>(promise: Promise<TResult>) => {
  return promise
    .then(data => [data, null] as const)
    .catch(err => [null, err] as const);
};

修复后变量a的类型会被正确推断为{ a: number } | null,b的类型会被推断为Error | null。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 00:00:00