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

TypeScript中如何通过关键字映射存储并检索类构造函数?

TypeScript 实现关键字映射 Feature 类方案

首先明确核心点:TypeScript 泛型是编译时特性,运行时无法直接通过泛型获取类型,所以必须显式传入类的构造函数。

1. 定义基础类型与接口

先声明接口和构造函数类型,约束所有符合要求的 Feature 类:

interface ISomeFeature {
  execute(): Promise<void>;
}

// 定义构造函数类型:无参,返回 ISomeFeature 实例
type FeatureConstructor = new () => ISomeFeature;

2. 实现配置映射类

在配置类中用 Map<string, FeatureConstructor> 存储关键字到构造函数的映射,完善 map 和 get 方法:

class FeatureConfig {
  private myMap: Map<string, FeatureConstructor> = new Map();

  // 泛型约束确保传入的构造函数符合接口要求
  map<T extends ISomeFeature>(key: string, constructor: new () => T) {
    this.myMap.set(key, constructor);
  }

  get(key: string): ISomeFeature | undefined {
    const constructor = this.myMap.get(key);
    if (!constructor) return undefined;
    return new constructor();
  }
}

3. 使用示例

定义自定义 Feature 类,通过配置类映射并实例化:

class CustomFeature implements ISomeFeature {
  async execute() {
    console.log("CustomFeature 执行逻辑");
  }
}

// 初始化配置
const config = new FeatureConfig();
// 关联关键字与构造函数
config.map("theKey", CustomFeature);

// 检索并创建实例
const instance = config.get("theKey");
if (instance) {
  instance.execute(); // 输出 "CustomFeature 执行逻辑"
}

关键说明

  • 必须显式传入构造函数:TypeScript 泛型在运行时会被擦除,无法仅通过 map<CustomFeature>("theKey") 这种泛型写法获取类的构造函数,必须传递实际的构造函数引用。
  • 类型安全保障:FeatureConstructor 类型确保了存储的构造函数都能生成符合 ISomeFeature 接口的实例,避免类型不匹配问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 10:35:17