我有一个抽象类,它将接受传递到构造函数中的任何数据,并将其分配给实例.目标是您可以使用实例数据的子集来初始化实例.
我遇到的问题是,一旦扩展了抽象类,子类构造函数就需要一个类型为Partial<AbstractParent>
的参数,而不是Partial<Child>
.
我已经能够使用静态的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';
}
const myResource = new MyResource({ someField: 'hello world' });
//this produces an error "Argument of type '{ someField: string; }' is not assignable to parameter of type 'Partial<Resource>'"
const anotherResource = MyResource.create({ someField: 'hello world' });