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

TypeScript带默认类型泛型函数返回类型推断问题及方案咨询

TypeScript泛型函数ReturnType推断问题解析

为什么T1的类型是{ a: unknown; b: unknown }?

这不是Bug,是TypeScript的设计逻辑导致的。当直接获取typeof test时,得到的是未指定泛型参数的泛型函数类型,此时TypeScript不会自动应用默认泛型参数,而是将泛型参数视为未约束的类型变量。ReturnType作用于这种未实例化的函数类型时,会把泛型参数推断为unknown——因为默认参数只有在显式调用函数或显式指定泛型参数时才会生效,未绑定具体类型的泛型函数不会自动触发默认值填充。

除了T2的写法,还有哪些可行的解决方案?

  • 显式指定全部默认泛型参数:
    type T3 = ReturnType<typeof test<number, string>>; // { a: number; b: string }
    
  • 创建绑定默认泛型的类型别名:
    type TestWithDefaults = typeof test<number, string>;
    type T4 = ReturnType<TestWithDefaults>; // { a: number; b: string }
    
  • 用类型工具自动提取并应用默认参数:
    自定义类型工具获取泛型函数的默认参数,再自动应用:
    type ExtractDefaultGenerics<T> = 
      T extends <A = infer DA, B = infer DB>(a: A, b: B) => any 
        ? [DA, DB] 
        : never;
    
    type TestDefaults = ExtractDefaultGenerics<typeof test>; // [number, string]
    type T5 = ReturnType<typeof test<TestDefaults[0], TestDefaults[1]>>; // { a: number; b: string }
    
  • 封装无泛型的默认版本函数:
    如果不需要泛型灵活性,可以写一个固定默认类型的包装函数:
    const testDefault = (a: number, b: string) => test(a, b);
    type T6 = ReturnType<typeof testDefault>; // { a: number; b: string }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 04:33:31