如何在TypeScript抽象类构造函数中获取子类类型?
TypeScript抽象类子类构造函数参数类型不符合预期
我定义了抽象类Resource,其构造函数通过Object.assign将传入的数据分配给实例,目的是支持用数据子集初始化实例。但子类继承后,构造函数要求的参数类型是Partial<Resource>,而非预期的Partial<子类>。
目前已通过静态create方法、泛型及this参数实现了类似逻辑,但希望直接通过构造函数达成需求。
可复现代码
interface ResourceConstructor { new(data: Partial<Resource>): Resource create<T extends ResourceConstructor>(this: T, data: Partial<InstanceType<T>>): InstanceType<T>; } abstract class Resource { public abstract id: number; constructor(data: Partial<Resource>) { Object.assign(this, data); } static create<T extends ResourceConstructor>(this: T, data: Partial<InstanceType<T>>): InstanceType<T> { const instance = new this(data) as InstanceType<T>; return instance; } } class MyResource extends Resource { id: number = 1; someField: string = 'value'; } // 报错:类型“{ someField: string; }”的参数不能赋给类型“Partial<Resource>”的参数 const myResource = new MyResource({ someField: 'hello world' }); // 此方法可以正常工作 const anotherResource = MyResource.create({ someField: 'hello world' });
解决方案
通过给抽象类添加递归泛型约束,让构造函数参数类型与子类实例类型绑定,即可实现需求:
abstract class Resource<T extends Resource<T>> { public abstract id: number; // 参数类型改为 Partial<T>,与子类实例类型关联 constructor(data: Partial<T>) { Object.assign(this, data); } // 简化静态 create 方法的类型定义 static create<T extends Resource<T>>(this: new (data: Partial<T>) => T, data: Partial<T>): T { return new this(data); } } // 子类继承时传入自身类型作为泛型参数 class MyResource extends Resource<MyResource> { id: number = 1; someField: string = 'value'; } // 现在可以正常调用构造函数,无类型错误 const myResource = new MyResource({ someField: 'hello world' }); const anotherResource = MyResource.create({ someField: 'hello world' });
核心说明:
- 递归泛型
T extends Resource<T>强制子类传入自身类型,确保构造函数能识别子类的属性 - 构造函数参数
Partial<T>会自动适配子类类型,替换原有的Partial<Resource> - 静态方法的类型约束更简洁,无需额外类型断言
这样修改后,子类构造函数就能正确接受Partial<子类>类型的参数,完全满足用数据子集初始化实例的需求。
内容的提问来源于stack exchange,提问作者heavygl0w
相关产品推荐
相关产品推荐

