I’m learning object-oriented programming in JavaScript and wondering, does JavaScript have an interface type similar to Java’s interface keyword? I’d like to create something like a listener, but I’m not sure how or if it’s possible using a JavaScript interface approach.
I’ve been working with JavaScript for over a decade, and one thing folks often ask is, Does JavaScript support interfaces like Java? Technically, no. But you can mimic them using JSDoc and a bit of convention.
In JavaScript, while there’s no native support for interfaces like in Java, you can simulate a javascript interface using JSDoc annotations and prototype-based inheritance. For example, you can define a function called ListenerInterface
and annotate it with @interface
using JSDoc. Then, you define a method on its prototype—like onEvent()
—that throws an error if it’s not overridden. This sets up an expectation that any object claiming to implement this interface must define the onEvent
method.
To implement this interface, you create a constructor function MyListener
, set its prototype to inherit from ListenerInterface.prototype
using Object.create
, and then override the onEvent
method with your own implementation (like logging the event to the console).
However, if you’re seeing an error, it’s likely because you forgot to set the constructor
back to MyListener
after using Object.create
. Here’s how to fix that:
function MyListener() {}
MyListener.prototype = Object.create(ListenerInterface.prototype);
MyListener.prototype.constructor = MyListener; // <-- This line fixes the constructor
MyListener.prototype.onEvent = function(event) {
console.log('Event received:', event);
};
This approach relies on discipline and documentation—it won’t enforce the interface at runtime unless you add manual checks—but it’s a common workaround when working with traditional JavaScript before adding something like TypeScript.
This kind of “gentleman’s agreement” works decently—you’re basically documenting a javascript interface contract and relying on other devs to stick to it. Not foolproof, but better than nothing!
Totally agree with @dimplesaini.230. I’ve used that approach myself, but in bigger codebases, you often want some validation at runtime too. I usually add a manual method checker to make sure the object really fits the javascript interface expectations:
function implementsInterface(obj, methods) {
return methods.every(method => typeof obj[method] === 'function');
}
const listener = {
onEvent: function(evt) { console.log(evt); }
};
if (implementsInterface(listener, ['onEvent'])) {
listener.onEvent('Hello!');
} else {
throw new Error('Object does not implement required interface');
}
Still not bulletproof, but it gives you an extra safety net, especially when onboarding new devs or working on large, modular systems.