how to do interface inheritance with multple types in javascript

In JavaScript, we don't have interfaces like other OOP languages. However, we can achieve interface-like functionality using objects.

To implement interface inheritance with multiple types, we can create an object that serves as the interface and then extend it to our classes.

Here's an example:

index.tsx
// Interface object
const interfaceObj = {
  method1: function() {},
  method2: function() {}
};

// Class A
class ClassA {
  constructor() {}

  method1() {
    console.log('ClassA: Method1');
  }
}

// Class B
class ClassB {
  constructor() {}

  method2() {
    console.log('ClassB: Method2');
  }
}

// Implement interface
class ClassC extends interfaceObj {
}

// Instantiate classes
const a = new ClassA();
const b = new ClassB();
const c = new ClassC();

// Call methods
a.method1(); // ClassA: Method1
b.method2(); // ClassB: Method2
c.method1(); // Throws TypeError: c.method1 is not a function
c.method2(); // Throws TypeError: c.method2 is not a function
666 chars
39 lines

In this example, we define an object interfaceObj that represents our interface. We then define two classes, ClassA and ClassB, each with their own unique methods that align with the interface methods we defined.

We then implement the interface by creating a new class ClassC that extends the interface object interfaceObj. This allows ClassC to have access to the interface methods, but it doesn't implement them, so trying to call them will result in a TypeError.

We can then instantiate ClassA, ClassB, and ClassC and call their respective methods.

This approach allows us to define what an interface should look like and make sure that classes implement it correctly.

gistlibby LogSnag