I'm struggling to create a versatile inheritance class for my services. Currently, I have two service classes named Service_A and Service_B that essentially do the same thing. However, Service_A works with Class_A while Service_B works with Class_B. The only difference between them is the type they work with.
My goal is to consolidate the code into a more generic class (EntityService) that both Service_A and Service_B can inherit from. This way, I can write the code once and reuse it without having to override all methods or specify types in each method call.
Here's how EntityService looks like:
declare class Observable<T> { x: T }
declare class Actor {
doStuff<T>(anything: T): T[];
getData<I>(): I;
getObservable<U, I>(data: I): Observable<U[]>;
}
interface Entity {
param_1: number,
param_2: number,
}
class EntityObj {
id: string;
param_1: number;
param_2: number;
constructor(id: string, param_1: number, param_2: number) {
this.id = id;
this.param_1 = param_1;
this.param_2 = param_2;
}
static fromInterface(entity: Entity, id: string): EntityObj {
return new this(id, entity.param_1, entity.param_2);
}
}
export class EntityService {
/* Desired functionality:
* static classTypeAlias: EntityObj;
* static interfaceTypeAlias: Entity;
*/
constructor(private readonly actor: Actor) {}
getEntityObjs(): Observable<EntityObj[]> | null {
let data: Entity = this.actor.getData()
let entityObjs: Observable<EntityObj[]> = this.actor.getObservable<EntityObj, Entity>(data);
return entityObjs;
}
getObjFromInterface(): EntityObj {
let entityObj: EntityObj = EntityObj.fromInterface(this.actor.getData(), "foo");
return entityObj;
}
update(entity: EntityObj): void { let entityDoc = this.actor.doStuff<Entity>(entity); }
}
I want Service_A to be able to use methods like update() with a parameter of type "Class_A" implicitly, and getEntityObjs() to return something of type "Observable<Class_A[]> | null" implicitly as well.
I tried exploring generic types but couldn't figure out how to avoid extending them from EntityObj when accessing properties or using their values associated with the class (like
class EntityService<classType, interfaceType> {...}
) to define argument/return types.
If you have any advice or suggestions on how to solve this issue using proper techniques, please share them. Your help would be greatly appreciated!