Caio Amaral

How to prevent inheritance on TypeScript/JavaScript

“There is no direct way to prevent subclassing in TypeScript. The indirect way is to add a check in the constructor to prevent instantiating a different prototype from the one creating the object:

class A {

  constructor() {

     this.subClassCheck();

  }

  private subClassCheck(): never | void {

     if (Object.getPrototypeOf(this) !== A.prototype) {

        throw new Error("Cannot extend this class.");

     }

  }

}

class B extends A {}

let a = new A(); // OK

let b = new B(); // fail