Loeka Lievens
Loeka Lievens

Reputation: 41

Multiple classes that have a different name but extends the same class

I have for example this class:

abstract class MyClass {
  abstract myProp: number;

  constructor() {
    // Some code
  }
}

So I want to create multiple classes that extends this class. But I don't want to repeat it multiple times as I will have a lot of classes. So the purpose is that each class has a different name and myProp.

For example:

class FirstClass extends MyClass {
  myProp = 1;
  constructor() {
    super();
    // Some code
  }
}

class SecondClass extends MyClass {
  myProp = 2;
  constructor() {
    super();
    // Some code
  }
}

So I want to generate these classes (with for example a function) but the problem is that I will have to use the new keyword. So the usage for each of these classes should be like this:

const myConst = new FirstClass();
const myConst2 = new SecondClass();

I hope this makes some sense. I just don't want to repeat every class because it has a different name and myProp.

Upvotes: 3

Views: 913

Answers (2)

Linda Paiste
Linda Paiste

Reputation: 42228

You can create classes through a function that returns an anonymous class.

const createClass = ( prop: number ) => {
    return class extends MyClass {
        myProp: number;

        constructor () {
            super();
            this.myProp = prop;
        }
    }
}

const FirstClass = createClass(1);

const x = new FirstClass();
console.log(x.myProp);

Or check out the answers to these questions for ideas:

Upvotes: 2

Producdevity
Producdevity

Reputation: 882

If I understand your problem correctly, you could just pass the variable that's different as an argument in the constructor.

class MyClass {
  myProp: number;

  constructor(myProp: number) {
    this.myProp = myProp
    // Some code
  }
}

And then create the class instances you want.

const myConst = new MyClass(1);
const myConst2 = new MyClass(2);

Personally, I would only extend a class if I want to add some methods or properties that aren't shared. Since myProp exists in both classes, it's probably better to just pass the value to the constructor.

Upvotes: 0

Related Questions