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

TypeScript如何基于TestType定义实现showTest函数入参对应动态返回类型

TypeScript 动态返回类型实现方案

完全可以实现该需求,以下是两种可行的实现方式:

方案1:泛型 + 索引访问类型(推荐)

直接复用你已定义的TestType映射关系,扩展性更好,后续新增枚举值不需要修改函数逻辑:

  1. 首先给someObject显式添加TestType类型注解,保证内部取值类型正确
  2. 给函数添加泛型约束,返回值类型直接关联入参对应的TestType索引类型

修改后完整代码:

enum TestEnum {
  ONE= 'one',
  TWO= 'two'
}

type TestType = {
  [TestEnum.ONE]: boolean;
  [TestEnum.TWO]: number
}

// 显式声明类型,避免类型推导偏差
const someObject: TestType = {
  [TestEnum.ONE]: true,
  [TestEnum.TWO]: 123
}

// 泛型T约束为TestEnum的子类型,返回值自动匹配TestType的对应类型
const showTest = <T extends TestEnum>(value: T): TestType[T] => {
  const result = someObject[value];
  if (typeof result === 'undefined') {
    throw new Error(`Unable to find ${value} in object`);
  }
  return result;
};

// 调用时自动推导返回类型
showTest(TestEnum.ONE) // 类型为boolean,返回值为true
showTest(TestEnum.TWO) // 类型为number,返回值为123

方案2:函数重载

适合枚举值固定、不需要频繁扩展的场景,类型定义更直观:

// 重载声明
function showTest(value: TestEnum.ONE): boolean;
function showTest(value: TestEnum.TWO): number;
// 函数实现
function showTest(value: TestEnum) {
  const result = someObject[value];
  if (typeof result === 'undefined') {
    throw new Error(`Unable to find ${value} in object`);
  }
  return result;
}

该方案的缺点是后续TestEnum新增枚举值时,需要同步新增对应的重载声明,维护成本更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 10:24:02