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.