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

Promise.all中TypeScript类型实例化过深错误的排查与解决

Type instantiation is excessively deep and possibly infinite 错误分析与修复

错误原因

当用Promise.all批量调用泛型的getT函数时,TypeScript会尝试把所有Promise的返回值合并成元组类型进行推导。每个getT返回的翻译函数本身带有复杂的泛型约束(比如关联不同语言的消息类型),多个这类复杂类型叠加后,会让TypeScript的类型推导器陷入深度递归计算,超出它的类型处理上限,因此抛出这个错误。单独调用时只有单个泛型类型,推导压力小,所以不会触发错误。

修复方案

1. 给Promise.all显式指定返回类型

直接告诉TypeScript最终的结果类型,跳过自动推导:

// 先定义翻译函数类型
type Translator<Locale extends string> = (key: string) => string;

// 显式指定元组类型
const [tEn, tZh] = await Promise.all<[Translator<'en'>, Translator<'zh'>]>([
  getT('en'),
  getT('zh')
]);

2. 简化getT的返回类型定义

把翻译函数的类型抽成独立的顶层类型,减少TypeScript推导时的复杂度:

// 提前定义翻译函数结构
type TranslationFn<L extends string> = (key: keyof Messages<L>) => string;

// 让getT直接返回这个预定义类型
async function getT<L extends string>(locale: L): Promise<TranslationFn<L>> {
  const messages = await import(`./locales/${locale}.json`);
  return (key) => messages[key];
}

// 此时Promise.all的类型推导会更顺畅
const [tEn, tZh] = await Promise.all([getT('en'), getT('zh')]);

3. 用类型断言临时绕过(应急方案)

如果上面的方法都不适用,可临时用类型断言跳过复杂推导,但不推荐长期使用:

const [tEn, tZh] = await Promise.all([
  getT('en'),
  getT('zh')
]) as [ReturnType<typeof getT<'en'>>, ReturnType<typeof getT<'zh'>>];

4. 拆分调用,避免批量推导

把多个await拆成单独调用,不让TypeScript同时处理多个复杂泛型:

const tEn = await getT('en');
const tZh = await getT('zh');
// 后续正常使用tEn和tZh即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 17:11:13