Skip to content Skip to sidebar Skip to footer

Assigning Child Class To A Parent Class Typed Property

I do have the following 2 base clases: class BaseModel {} class BaseService{ protected model:BaseModel; } Now I want to implement BaseHelper and BaseService for a specific use

Solution 1:

You need to instantiate MyModel using the new keyword (new MyModel()). You assigned the actual class (model = MyModel) instead of an instance of it.

Also, you might want to make BaseServicegeneric:

classBaseModel {}

classBaseService<T extendsBaseModel> {
    protectedmodel: T;

    constructor(model: T) {
        this.model = model;
    }
}

classMyModelextendsBaseModel{}

classMyServiceextendsBaseService<MyModel> {
    constructor() {
        super(newMyModel());
    }
}

(code in playground)


Edit

If you need the class and not the instance, then something like:

classBaseModel {}

typeBaseModelConstructor= { new(): BaseModel };

classBaseService {
    protected modelCtor: BaseModelConstructor;
}

classMyModelextendsBaseModel {}

classMyServiceextendsBaseService {
    modelCtor = MyModel;  
}

(code in playground)

Or you can use generics here as well:

classBaseModel {}

type BaseModelConstructor<T extendsBaseModel> = { new(): T };

classBaseService<T extendsBaseModel> {
    protected modelCtor: T;
}

classMyModelextendsBaseModel {}

classMyServiceextendsBaseService<BaseModel> {
    modelCtor = MyModel;  
}

(code in playground)


If your derived classes have different ctor signatures then you can either deal with it in the base ctor type:

type BaseModelConstructor<T extends BaseModel>={ new(...args:any[]):T};

Here you can pass any count and kind of parameters, but you can also supply different signatures:

type BaseModelConstructor<T extends BaseModel> = { 
    new(): T;
    new(str: string): T;
    new(num: number, bool: boolean): T;
};

But you can also use a different type per derived class:

type MyModelConstructor = { new(param: string): MyModel };

Solution 2:

model should be an instance of MyModel:

classMyModelextendsBaseModel{}

classMyServiceextendsBaseService {
  model = newMyModel()
}

Solution 3:

Use instance of BaseModel

classMyServiceextendsBaseService {
  model = newMyModel();  
}

Post a Comment for "Assigning Child Class To A Parent Class Typed Property"