I'm mocking an interface class:
const error = "Child must implement method";
class MyInterface
{
normalFunction()
{
throw error;
}
async asyncFunction()
{
return new Promise(() => Promise.reject(error));
}
}
class MyImplementation extends MyInterface
{
}
If any of the interface methods are called without an overridden implementation, the error gets thrown. However these errors will only appear at time of execution.
Is there a way to check that the functions were overridden at construction?
You could add some inspection in the constructor of MyInterface, like this:
class MyInterface {
constructor() {
const proto = Object.getPrototypeOf(this);
const superProto = MyInterface.prototype;
const missing = Object.getOwnPropertyNames(superProto).find(name =>
typeof superProto[name] === "function" && !proto.hasOwnProperty(name)
);
if (missing) throw new TypeError(`${this.constructor.name} needs to implement ${missing}`);
}
normalFunction() {}
async asyncFunction() {}
}
class MyImplementation extends MyInterface {}
// Trigger the error:
new MyImplementation();
Note that there are still ways to create an instance of MyImplementation without running a constructor:
Object.create(MyImplementation.prototype)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With