Home > Software design >  import child class inside parent class in javascript
import child class inside parent class in javascript

Time:11-01

I have a class hierarchy, like Parent, Child1 that extends the Parent, Child2 etc. Parent stores an array of child items and I need to import Child1 and Child2 inside Parent.

That obviously leads to circular dependency and throws while trying to create either Child1 or Child 2 with the below error:

TypeError: Super expression must either be null or a function

What are the options to resolve that?

For example, consider the following structure:

parent.js

export default class Parent {
    itemArray = []
}

child1.js

import Parent from "./parent.js"
export default class Child1 extends Parent {
}

child2.js

import Parent from "./parent.js"
export default class Child2 extends Parent {
}

itemArray recursively stores either Child1 or Child2

Now I need to type annotate the itemArray so the parent.js becomes like below:

parent.js

import Child1 from "./child1"
import Child2 from "./child2"

export default class Parent {
    @Types(() => [Child1, Child2])
    itemArray = []
}

This annotation allows to assign correct class to each item in the array when the final object is constructed from a plain object. But that's the details. The question is:

How to allow such a structure so it doesn't brake the entire hierarchy?

CodePudding user response:

The solution is simple and clear to understand. The idea behind the solution is importing classes hierarchical in a different module.

// internal.js (New Js File)
// This module imports and exports
// Parent and Child classes will import classes from here.

export { Parent } from "./parent.js";
export { Child1 } from "./child1.js";
export { Child2 } from "./child2.js";

And you can import required class from 'internal.js'. As an example:

// parent.js

import { Child1 } from "./internal.js";
import { Child2 } from "./internal.js";

export class Parent {
     // @Types annotation method here..
     itemArray = [];
}

Output:

// index.js file to output result

import { Parent } from "./internal.js";
import { Child1 } from "./internal.js";
import { Child2 } from "./internal.js";

var child1 = new Child1();
var child2 = new Child2();
var parent = new Parent();

parent.itemArray.push(child1);
parent.itemArray.push(child2);


console.log(parent.itemArray.length); //it prints '2'
  • Related