Class constructor cannot be invoked without 'new' in TS

avatar

Borislav Hadzhiev

Last updated: Mar 14, 2022

banner

Check out my new book

Class constructor cannot be invoked without 'new' in TS #

The "Class constructor cannot be invoked without new" error occurs when the target property in tsconfig.json is set to lower than es6 or you instantiate a class without the new operator. To solve the error, set target to es6 and use the new operator when instantiating classes.

The first thing you should do is open your tsconfig.json file and make sure target is set to es6 or more recent.

tsconfig.json
{ "compilerOptions": { "target": "es6", // ... your other options } }

The target option sets the language version for the emitted JavaScript files.

All modern browsers (and Node.js) support all ES6 features. When your target option is set to something older than es6 (e.g. es5), TypeScript has to transpile your classes to functions, which could be problematic in some cases.

If this is the cause of the error, setting target to es6 should resolve it.

You might also be getting the error if you forgot to use the new operator when instantiating a class in TypeScript.

index.ts
class Employee { constructor(public name: string, public salary: number) { this.name = name; this.salary = salary; } } // ⛔️ Error: Class constructor Employee cannot be invoked without 'new' const employee = Employee('James', 100);

To get around this, always make sure to use the new operator when creating instances of a class.

index.ts
class Employee { constructor(public name: string, public salary: number) { this.name = name; this.salary = salary; } } // ✅ Works const employee = new Employee('James', 100); console.log(employee.name); // 👉️ "James" console.log(employee.salary); // 👉️ 100

We used the new operator upon class instantiation. The new operator does 3 things:

  1. Creates a new object that inherits the prototype of the class
  2. Calls the constructor function with the provided parameters and binds the this keyword to the newly created object
  3. Returns the newly created object
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.