I have grouped my TypeScript
classes in the same .ts file due to import dependencies. I am seeking assistance to refactor the code and eliminate the circular reference of imports:
First, let's consider the abstract class GenericModel
:
export abstract class GenericModel {
nodeClass: string;
id: string = "0";
static fromJson(json: any): GenericModel {
if (json.nodeClass === "Entity") {
return EntityModel.fromJson(json);
}
else if(json.nodeClass === "User") {
return UserModel.fromJson(json);
}
return null;
}
}
The next two classes are EntityModel
(shown below) and UserModel
:
export class EntityModel extends GenericModel {
nodeClass: string = "Entity";
alias: string;
description: string;
constructor(public text: string, public id: string, public uuid: string, alias: string, public rand:string = "") {
//[...]
}
//instance methods
//[...]
public static fromJson(json: any): EntityModel {
var entity = new EntityModel(json.text, json.id, json.uuid, json.alias, json.rand);
entity.description = json.description;
if (json.types) {
for (let type of json.types) {
let objectifiedType: EntityModel = EntityModel.fromJson(type);
entity.types.push(objectifiedType);
}
}
if (json.innerEntities){
for (let innerEntity of json.innerEntities) {
let objectifiedInnerEntity: EntityModel = EntityModel.fromJson(innerEntity);
entity.innerEntities.push(innerEntity);
}
}
return entity;
}
}
I am currently performing JSON deserialization using a hierarchy of static calls fromJson()
based on the nodeClass
.
If the GenericModel
were in a separate file, it would require imports from EntityModel
and UserModel
, whereas the other two classes, if in separate files, would need to import GenericModel
.
GenericModel --- has to import --> EntityModel, UserModel
EntityModel --- has to import --> GenericModel
UserModel --- has to import --> GenericModel
I am curious if there is a way to refactor the code to achieve the same functionality while having the classes in separate .ts files.
Thank you!