TypeError: x is not a constructor
TypeError: x is not a constructor in JavaScript means you used new on something that cannot be used with new: an arrow function, a plain object like Math, or undefined from a wrong import.
How do I fix TypeError: x is not a constructor?
TypeError: x is not a constructor means you wrote new x() but x is not a class or normal function. Often x is an arrow function, a plain object like Math, or the wrong thing from an import. Use a class for arrow functions, and import the named export, like const { Chart } = require("./chart").
- 1. Log typeof firstconsole.log(typeof Thing) before the new. "undefined" means a wrong import; "object" means it is not a class.
- 2. Match the exportCheck whether the other file uses a default or named export, and import it the same way.
- 3. Replace arrow functionsArrow functions cannot be used with new. Rewrite it as a class with a constructor.
What does TypeError: x is not a constructor mean?
new Thing() only works if Thing is a class or a normal function. Arrow functions, object methods written in shorthand, and built-in objects like Math and JSON cannot be used with new. Very often Thing is not the class at all but undefined or an object holding it, because the import picked the wrong name. Bundlers word this as "_chart.default is not a constructor" when a default import meets a file with only named exports.
Why does TypeError: x is not a constructor happen?
1. Using new with an arrow function
Arrow functions cannot be constructors. Use a class.
Breaks
const Point = (x, y) => {
this.x = x;
this.y = y;
};
const p = new Point(1, 2);Works
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
const p = new Point(1, 2);2. Importing the whole module instead of the class
If the file exports { Chart }, require() gives you an object that contains Chart, not Chart itself.
Breaks
// chart.js: module.exports = { Chart };
const Chart = require("./chart");
new Chart();Works
const { Chart } = require("./chart");
new Chart();3. Using new on an object, not a class
Math, JSON and plain objects are not classes. Use them directly.
Breaks
const m = new Math();
const r = m.random();Works
const r = Math.random();How to find it in your own code
Checklist: 1) console.log(typeof Thing) just before the new. If it prints "undefined", the import or the name is wrong; check the export in the other file. 2) If it prints "object", it is not a class; call its methods directly. 3) If it is your own arrow function, turn it into a class. 4) Check the library's docs for whether it uses a default or named export.
Practise type errors
None of the challenges raises this exact error yet. These practise the same kind of bug.
Still not sure why yours breaks?
Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.