Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if Child class has overridden Parent method/function?

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?

like image 389
sookie Avatar asked Nov 02 '25 05:11

sookie


1 Answers

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)
like image 132
trincot Avatar answered Nov 03 '25 19:11

trincot