You need to enable JavaScript to run this app. TypeScript泛型类中将泛型T作为值使用为什么会触发编译器报错?
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript泛型类中将泛型T作为值使用为什么会触发编译器报错?

报错原因
  • TypeScript 的泛型属于静态类型系统特性,仅在编译阶段做类型校验,编译为 JavaScript 后所有泛型、类型注解都会被完全擦除,运行时不存在 T 这个实体值。
  • 你代码中 create 方法要求传入的参数是「构造函数」这个实际运行时存在的值,而 T 只是编译期的类型标记,不属于运行时值,因此直接传 T 或者写 new T() 都会被编译器判定为「把类型当值使用」的错误。
解决方案

核心逻辑是:必须给 Factory 传入泛型 T 对应的真实构造函数,才能在运行时调用创建实例,有两种常用实现方式:

方案1:实例化Factory时传入构造函数

适合同一个Factory实例固定生产某一类对象的场景,代码示例:

class Factory<T> {
    // 存储泛型对应的实际构造函数
    private tCreator: new () => T;

    // 初始化时传入构造函数
    constructor(tCreator: new () => T) {
        this.tCreator = tCreator;
    }

    create(): T {
         return new this.tCreator();
    }

    test(json: string) {
        let a: T = this.create();
        let a2: T = new this.tCreator();
    }
}

// 使用示例
class User {
    name = 'test'
}
// 传入User构造函数,生成专门生产User实例的工厂
const userFactory = new Factory(User);
const user = userFactory.create(); // 自动推断类型为User

方案2:调用方法时动态传入构造函数

适合同一个Factory实例需要生产多种类型对象的场景,代码示例:

class Factory {
    // 把泛型定义在方法层面,调用时动态绑定类型
    create<T>(tCreator: new () => T): T {
         return new tCreator();
    }

    test<T>(tCreator: new () => T, json: string): T {
        let a: T = this.create(tCreator);
        return a;
    }
}

// 使用示例
class User {}
class Order {}
const factory = new Factory();
const user = factory.create(User); // 类型为User
const order = factory.create(Order); // 类型为Order

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

相关产品推荐
方舟 Agent Plan

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

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