How to fix “TypeError: Right-hand side of ‘instanceof’ is not callable” when I use another module class?

The problem is that you have a circular dependency. The other file requires indexindex requires Transaction, and Transaction requires index. So, when transaction runs, it tries to require indexwhose module is already in the process of being builtindex hasn’t exported anything yet, so requiring it at that time results in an empty object.

Because both must call each other, one way to solve it would be to put both classes together, and export them both:

// index.js
class Context {
  constructor(uid) {
    if (typeof uid !== "string") throw new TypeError("uid must be a string.");

    this.uid = uid;
  }

  runTransaction(operator) {
    return new Promise((resolve, reject) => {
      if (typeof operator !== "function")
        throw new TypeError(
          "operator must be a function containing transaction."
        );

      operator(new Transaction(this));
    });
  }
}

class Transaction {
  constructor(context) {
    // check type
    if (!(context instanceof Context))
      throw new TypeError("context should be type of Context.");

    this.context = context;
    this.operationList = [];
    console.log("successfully constructed transaction");
  }

  addOperation(operation) {}
}

module.exports = { Context, Transaction };

and

const { Context, Transaction } = require("./index");
const context = new Context("some uid");
context.runTransaction(transaction => {});

Leave a Comment