I have a number of models that will be acted upon by their related controller. However there is a bit of boilerplate I would like to factor out of each controller and I thought I might be able to use a "base controller" with generics.
Hopefully example below shows what I am trying to accomplish - instantiate each controller with a factory method which will result in an instance of the controller being returned containing its specific model instantiated with its defaults.
The challenge specifically is that I can't seem to get past the
'X' only refers to a type, but is being used as a value here
error in the factory. The abstract class model seems to be the right approach, but open to all suggestions. Playground
abstract class ModelA {
propA: string;
propB?: number;
propC?: number;
constructor() {
this.propA = "here"
}
}
interface ModelB {
propA: string,
propB: number,
propC: number,
}
class BaseController<X> {
private _model: X
constructor(payload: X) {
this._model = payload
}
public factory():BaseController<X>
{
let model:X;
model = new X();
return new BaseController<X>(model);
}
}
class ModelAController extends BaseController<ModelA> {
constructor(payload: ModelA) {
super(payload);
}
}
let x = ModelAController.factory();