DEV Community

Discussion on: A deep dive into ES6 Classes

Collapse
 
eppak profile image
Alessandro Cappellozza • Edited

Have you some tips (or best practice) to remediate the absence of interfaces? This is one of the reasons i stay away from plain js and adopt ts.

Collapse
 
mustapha profile image
Mustapha Aouas • Edited

Hi Alessandro,

That's a great question. Of course in JS there's no such thing as an Interface, but the entire idea of the interface segregation principle (from the 4th design principle in SOLID) is about segregating interfaces and making them smaller. This principle is applicable in JS even if there's no interfaces.

We can use class inheritance + prototypal composition. Here is an example:

class Vehicle {
  numberOfPassengers = 0;

  constructor(nb) {
    this.numberOfPassengers = nb;
  }
}

const hasEmergencyExit = {
  performAnEmergencyExit() {
    this.numberOfPassengers = 0;
  }
}
// or like this if we want the functionality to be more configurable
const hasEmergencyExitV2 = (nb) => ({
  performAnEmergencyExit() {
    this.numberOfPassengers = nb;
  }
});

// ---

class Car extends Vehicle {
  constructor() {
    super(5);
  }
}
Object.assign(Car.prototype, hasEmergencyExit);

const car = new Car();
car.performAnEmergencyExit();
Enter fullscreen mode Exit fullscreen mode

So the Car extends the Vehicle class, then we take the prototype of that Car class (which is basically the definition of that class) and we are adding in the functionality of hasEmergencyExit.


 

I don't know if it's a best practice, but that's how i would remediate the absence of interfaces. That being said, I know that this is quite different from how we usually use interfaces, and typescript can make that very straight forward and easy.

Collapse
 
eppak profile image
Alessandro Cappellozza

Thank you for the reply and the code, i asked because more or less all patterns are based on the interface priciple and is hard to use something that imitate the funcionality without a explicit support. Maybe can be a topic for a new awesome post like this one

Some comments have been hidden by the post's author - find out more