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

TypeScript中infer关键字与独立类型的编译性能对比

TypeScript类型定义:infer内联方式 vs 独立类型定义的编译性能对比

定义独立类型的写法(也就是拆分出_ComplexThing<T>的ComplexThing方式),编译性能要显著优于使用infer配合extends检查的内联写法。

核心原因有两点:

  • 类型缓存效率更高:按照TypeScript性能Wiki里「命名复杂类型」的建议,独立命名的_ComplexThing<T>会被编译器纳入缓存体系。每次用到ComplexThing<T>时,编译器可以直接复用之前计算好的_ComplexThing<T>结果,不用重复执行内部的条件分支逻辑。而内联的ComplexThingInline<T>是一个整体的条件类型,编译器很难拆分出可复用的子部分,每次计算都要从头执行完整的条件判断+infer推断流程。
  • 减少不必要的约束检查:独立写法里,DoMappedThing的泛型约束会直接作用于_ComplexThing<T>的结果,不需要额外的extends检查;但内联写法里的extends infer NewT extends Record<string, any>是重复做了一次约束校验,平白增加了编译器的计算开销。

结合你给出的代码示例来看:

type DoMappedThing<T extends Record<string, any>> = {
    [K in keyof T]: T[K]
};

// 内联使用infer的写法,性能较差
type ComplexThingInline<T> = (
    T extends number
    ? {num: 0}
    : T extends string
    ? {str: ""}
    : never
) extends infer NewT extends Record<string, any>
? DoMappedThing<NewT>
: never;

// 独立类型定义的写法,性能更优
type _ComplexThing<T> = 
    T extends number
    ? {num: 0}
    : T extends string
    ? {str: ""}
    : never;
type ComplexThing<T> = DoMappedThing<_ComplexThing<T>>;

如果你的实际场景中,_ComplexThing<T>的逻辑更复杂(比如多层嵌套条件、复杂映射或联合类型组合),这种性能差异会更明显——拆分独立类型能最大化利用TypeScript的缓存机制,减少重复计算的次数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 10:52:43