Being new to TypeScript, what is the best method to implement a static factory in a base class that instantiates the child class type. For instance, consider a findAl
You will need to pass the subtype constructor to the static function on the base type.
This is because the base class doesn't (and shouldn't) know anything about the subtypes to know which child constructor to use.
This is an example of how it might look - each subtype defines its own static findAll()
method that calls the standard behaviour on the parent class, passing the data and constructor along for the parent to use:
class BaseModel {
static data: {}[];
static _findAll(data: any[], Type): T[] {
return data.map((x) => new Type(x));
}
constructor(readonly attributes) {
}
}
class Model extends BaseModel {
static data = [{ id: 1 }, { id: 2 }];
constructor(attributes) {
super(attributes);
}
static findAll() {
return BaseModel._findAll(this.data, this);
}
}
const a = Model.findAll();