Home > Back-end >  TypeError: coolArr.printArray is not a function when importing npm package
TypeError: coolArr.printArray is not a function when importing npm package

Time:05-09

I created a package with an index.js that looks like this:

module.exports = class CoolArray extends Array {
  printArray() {
    console.log(this);
  }
}

I then use babel to transpile the code using es2015 syntax.

After linking my package to my test folder I can import and use my class just fine like this:

import CoolArray from 'package-name';

const coolArr = new CoolArray(1, 2, 3);

However, I can't use any of the classes functions on the coolArr object.

coolArr.printArray() gives me the error TypeError: coolArr.printArray is not a function. What am I doing wrong?

Ok I've found a solution. My index.js file now looks like this:

module.exports = class AsyncArray extends Array {
  constructor(...elements) {
    super(...elements);

    this.printArray = () => {
      console.log(this);
    }
  }
}

CodePudding user response:

This should work:

class CoolArray extends Array {
  printArray() {
    console.log(this);
  }
}

module.exports = {
    CoolArray,
};

Then it can be used like this:

import { CoolArray } from 'package-name';

const coolArr = new CoolArray(1, 2, 3);

CodePudding user response:

Refactoring my index.js file to look like this allows me to use the class functions without any error:

module.exports = class AsyncArray extends Array {
  constructor(...elements) {
    super(...elements);

    this.printArray = () => {
      console.log(this);
    }
  }
}
  • Related