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

如何通过infer正确推断TypeScript函数的返回类型

解决TypeScript泛型自动推断返回类型的问题

问题原因

你当前的泛型写法中,编译器无法将第一个参数T的具体值与第二个参数S的类型做精准关联,导致S被推断为所有可能的联合类型,最终返回类型也变成了联合类型,而非你期望的精准类型。

解决方案1:使用函数重载

直接为每种输入组合定义重载签名,让编译器能根据传入的第一个参数匹配对应的重载,从而精准推断返回类型:

type Return<S> = {
    array: S extends 'number' ? number[] : S extends 'string' ? string[] : never;
    value: S extends 'number' ? number : S extends 'string' ? string : S extends 'object' ? object : never;
}

// 定义重载签名,明确每种输入对应的输出
function test(t: 'array', s: 'number'): number[];
function test(t: 'array', s: 'string'): string[];
function test(t: 'value', s: 'number'): number;
function test(t: 'value', s: 'string'): string;
function test(t: 'value', s: 'object'): object;

// 通用实现签名
function test<T extends 'array' | 'value', S>(t: T, s: S): Return<S>[T] {
    // 此处添加具体业务逻辑
    return {} as Return<S>[T];
}

// 测试验证
(() => {
    const x1 = test('array', 'number'); // 类型为number[] ✅
    const x2 = test('array', 'string'); // 类型为string[] ✅

    const y1 = test('value', 'number'); // 类型为number ✅
    const y2 = test('value', 'string'); // 类型为string ✅
    const y3 = test('value', 'object'); // 类型为object ✅
})();

解决方案2:优化泛型约束逻辑

重新设计F类型为映射类型,让S直接约束为F[T],明确T与S的依赖关系,帮助编译器精准推断:

type Return<S> = {
    array: S extends 'number' ? number[] : S extends 'string' ? string[] : never;
    value: S extends 'number' ? number : S extends 'string' ? string : S extends 'object' ? object : never;
}

// 调整F为映射类型,直接存储每种T对应的S可选值
type F = {
    array: 'number' | 'string',
    value: 'number' | 'string' | 'object'
};

function test<T extends keyof F, S extends F[T]>(t: T, s: S): Return<S>[T] {
    // 此处添加具体业务逻辑
    return {} as Return<S>[T];
}

// 测试验证
(() => {
    const x1 = test('array', 'number'); // 类型为number[] ✅
    const x2 = test('array', 'string'); // 类型为string[] ✅

    const y1 = test('value', 'number'); // 类型为number ✅
    const y2 = test('value', 'string'); // 类型为string ✅
    const y3 = test('value', 'object'); // 类型为object ✅
})();

方案说明

  • 函数重载方案:每个输入组合的类型都被明确声明,编译器匹配重载后能直接得到精准的返回类型,可读性强。
  • 优化泛型方案:通过映射类型F明确T与S的关联关系,让编译器在推断出T后自动缩小S的可选范围,进而正确计算Return<S>[T]的类型,写法更简洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 13:36:30