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

TypeScript如何根据入参对象的单个键值推导函数返回类型

类型优化与适配方案

你可以通过TS内置的索引访问类型 + 条件类型实现需求,完全不需要手动编写每个键对应的三元判断,同时自动适配三种入参场景:

核心思路

  1. 利用Potato[K]索引访问类型自动匹配键对应的类型,Potato结构变化时自动同步,无需手动维护映射
  2. 编写工具类型从入参中提取需要访问的键,自动适配字符串入参、对象入参、无参三种场景

完整实现代码

type OddParams = {
    thing: number;
    thing2: number;
    key?: PotatoKey;
}

type Banana = {
    id: string;
    name: string;
}

type Potato = {
    id: string;
    name: string;
    phone: number;
    monkey: Banana;
}

type PotatoKey = keyof Potato;
type Params = OddParams | PotatoKey;

// 工具类型:从入参中提取要访问的Potato键
type ExtractKeyFromParams<T extends Params | undefined> = 
  T extends undefined ? never :
  T extends PotatoKey ? T :
  T extends OddParams ? T['key'] : never;

// 函数类型定义
function getPotato<T extends Params | undefined = undefined>(
  desc?: T
): ExtractKeyFromParams<T> extends keyof Potato 
  ? Potato[ExtractKeyFromParams<T>] 
  : Potato 
{
    // 原有实现逻辑无需修改类型部分
    console.log(desc);
    return '2' as any
};

// 调用测试,类型全部符合预期
getPotato() // 返回类型 Potato
getPotato('id') // 返回类型 string
getPotato({thing: 2, thing2: 1, key: 'id'}) // 返回类型 string
getPotato({thing: 2, thing2: 1}) // 无key时返回类型 Potato

优势

  • 无需手动维护键与返回类型的映射关系,即使Potato有上百个字段也不需要修改类型逻辑
  • 自动适配所有入参场景,对象入参可选key的场景也能正确推导返回类型
  • 类型逻辑可读性高,后续维护成本极低

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 13:48:02