Search code examples
javascripttypescriptinheritanceparameter-passingsuper

Automate parameters passing to super()


I have a parent class such as:

class Animal {
  constructor({name, color}) {
    // Does something with name and color.
  }
}

Then I have many classes that extend Animal. For example:

class Lion extends Animal {
  constructor({name, color, tailLength}) {
    super({name: name, color: color})
    // Does something with tailLength.
  }
}

My problem is that this code is not very DRY. For example, I may need to add a new parameter to Animal:

class Animal {
  constructor({name, color, height}) {
    // Does something with name, color and height.
  }
}

Now I also need to change the interface of Lion and if I have 100 more classes who extend Animal I need to change those too.

Is there a way to rewrite this code so that all parameters of Animal are implicitly added to classes that extend it?


Solution

  • Since you use a single config-like object as any animal-related constructor's sole parameter, you should make use of the rest parameter syntax in order to allow a generic and extensible approach.

    class Animal {
      constructor({ name, color /* and anything the OP might furtherly want */ }) {
        // does currently something with name and color.
      }
    }
    class Lion extends Animal {
      constructor({ tailLength, ...configRest }) {
        super(configRest)
        // does something with tailLength.
      }
    }
    
    // usage ase e.g.
    const lion = new Lion({
      name: 'Simba', color: 'yellowish'/*, height*/, tailLength: 'long',
    });