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

TypeScript:如何根据枚举键设置函数的返回类型?

解决TypeScript枚举键对应返回类型的问题

你的代码核心问题有两个:

  1. 类型判断错误:TestKeys是默认的数字枚举,成员类型为number,所以typeof key === 'boolean'或'string'的判断永远不成立,TypeScript无法识别分支对应枚举的具体值。
  2. 泛型分支推断失效:使用泛型T时,TypeScript在函数内部无法确定T的具体类型,因此会要求返回值满足所有可能的SettingsKeyReturnType[T]的交集(即Test<boolean> & Test<string>),而A和B都不满足这个交集类型。

方案1:修正判断逻辑并使用类型断言

直接比较key与枚举成员,配合类型断言让TypeScript识别返回值与泛型的对应关系:

enum TestKeys {
  testBoolean,
  testString,
}

type SettingsKeyReturnType = {
  [TestKeys.testBoolean]: Test<boolean>,
  [TestKeys.testString]: Test<string>,
};

interface Test<T> {
  getData(): T;
}

class A implements Test<boolean> {
  getData(): boolean { return false; }
}

class B implements Test<string> {
  getData(): string { return 'test'; }
}

function buildTest<T extends keyof SettingsKeyReturnType>(key: T): SettingsKeyReturnType[T] {
  if (key === TestKeys.testBoolean) {
    return new A() as SettingsKeyReturnType[T];
  }
  if (key === TestKeys.testString) {
    return new B() as SettingsKeyReturnType[T];
  }
  
  throw new Error('Key not found');
}

方案2:使用函数重载(更推荐)

通过重载明确每个枚举输入对应的返回类型,无需断言,类型推断更清晰:

enum TestKeys {
  testBoolean,
  testString,
}

interface Test<T> {
  getData(): T;
}

class A implements Test<boolean> {
  getData(): boolean { return false; }
}

class B implements Test<string> {
  getData(): string { return 'test'; }
}

// 重载签名:明确输入与输出的对应关系
function buildTest(key: TestKeys.testBoolean): Test<boolean>;
function buildTest(key: TestKeys.testString): Test<string>;
// 实现签名:处理所有情况
function buildTest(key: TestKeys): Test<boolean> | Test<string> {
  if (key === TestKeys.testBoolean) {
    return new A();
  }
  if (key === TestKeys.testString) {
    return new B();
  }
  
  throw new Error('Key not found');
}

// 使用示例:类型推断正确
const booleanTest = buildTest(TestKeys.testBoolean); // booleanTest: Test<boolean>
const stringTest = buildTest(TestKeys.testString); // stringTest: Test<string>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 17:25:28