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

TypeScript中如何根据入参属性值精确缩小函数返回类型

TypeScript 入参属性关联返回类型推导解决方案

问题根因

原有代码中单独声明的泛型K未与入参optional的实际值做绑定推导,TS会默认将K推导为所有符合约束的联合类型'a' | 'b',因此T[K]最终会解析为string | number,无法缩小到具体属性的类型。

修复后完整代码

interface variousTypes {
    a: string;
    b: number;
}

interface always {
    neededAlways: any;
}

interface optional<TAttributes> extends always {
    optional?: keyof TAttributes | boolean;
}

// 修改泛型声明和返回值条件类型,用infer直接推导optional的具体值
declare function test<T extends variousTypes, O extends optional<T>>(options: O): 
    O extends { optional: boolean } ? 'extends-boolean' : 
    O extends { optional: infer K extends keyof T } ? T[K] :
    'base-type';

const a = test({
    neededAlways: 'test',
    optional: 'a'
}); // 类型正确推导为string

const b = test({
    neededAlways: 'test',
    optional: 'b'
}); // 类型正确推导为number

const c = test({
    neededAlways: 'test'
}); // 类型为'base-type',符合预期

const d = test({
    neededAlways: 'test',
    optional: true
}); // 类型为'extends-boolean',符合预期

核心修改点

  • 移除了原有提前声明的泛型K,避免TS泛型默认推导为联合类型
  • 在返回值条件类型中使用infer K extends keyof T直接从入参的optional属性中提取具体的键值,确保类型能精确缩小到对应属性的类型

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 00:06:01