Open In App

Implementing Interfaces in JavaScript

Last Updated : 07 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In JavaScript, there is no built-in concept of interfaces like you might find in languages like Java or C#. However, you can achieve similar functionality by defining and implementing your own interfaces using objects and classes. In this explanation, this article will guide you through the process of implementing interfaces in JavaScript.

Defining an Interface

In JavaScript, an interface can be thought of as a set of method signatures that a class must implement. You can define an interface as an empty object containing method names and their associated function signatures.

Example:

const MyInterface = {
method1: function () { },
method2: function (param1, param2) { },
};

Implementing the Interface

To implement an interface, you create a class and ensure that it contains methods with the same names and signatures as specified in the interface. If your class lacks any of the required methods, it won’t satisfy the interface.

Example:

class MyClass {
method1() {
console.log("Method 1 called");
}
method2(param1, param2) {
console.log(`Method 2 called with ${param1} and ${param2}`);
}
}

Checking for Interface Implementation

You can write a function to check if an object or class implements a specific interface. This function can iterate through the method names defined in the interface and verify their presence in the object or class.

Example: This example shows the implementation of a interface in JavaScript.

Javascript




const MyInterface = {
    method1: function () { },
    method2: function (param1, param2) { },
};
class MyClass {
    method1() {
        console.log("Method 1 called");
    }
 
    method2(param1, param2) {
        console.log(
            `Method 2 called with ${param1} and ${param2}`);
    }
}
 
function implementsInterface(obj, interfaceObj) {
    for (const method in interfaceObj) {
        if (!(method in obj) ||
            typeof obj[method] !== "function") {
            return false;
        }
    }
    return true;
}
 
const myObject = new MyClass();
 
if (implementsInterface(myObject, MyInterface)) {
    console.log(
        "myObject implements MyInterface");
} else {
    console.log(
        "myObject does not implement MyInterface");
}


Output

myObject implements MyInterface


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads