TS - 'new' expression whose target lacks construct signature

avatar

Borislav Hadzhiev

Sun Feb 27 20222 min read

banner

Photo by Ishan

TS - 'new' expression whose target lacks construct signature #

The "new expression, whose target lacks a construct signature" error occurs when we use the new keyword where it shouldn't be used or use it with a constructor function. To solve the error convert the constructor function to a class or remove the new keyword.

Sometimes the solution to the error is to remove the new keyword - if you aren't trying to create an instance of something, you shouldn't be using new.

Here is an example of how the error occurs.

index.ts
function Employee(fullName: string, salary: number) { this.fullName = fullName; this.salary = salary; this.getSalary = function () { return this.salary; }; } // ⛔️ Error: 'new' expression, whose target lacks a // construct signature, implicitly has an 'any' type.ts(7009) const emp1 = new Employee('James Doe', 100);

We used the new keyword with a constructor function and TypeScript complains, because it wants us to convert the constructor function to a class for better type checking.

To solve the error in this situation, convert the constructor function to a class.

index.ts
class Employee { constructor(public fullName: string, public salary: number) { this.fullName = fullName; this.salary = salary; } getSalary() { return this.salary; } } const emp1 = new Employee('James Doe', 100); console.log(emp1.fullName); // 👉️ "James Doe" console.log(emp1.getSalary()); // 👉️ 100

This class creates equivalent objects to the constructor function from the code snippet, but allows us to use the new keyword to create instances.

TypeScript offers much better type checking for classes than it does for constructor functions, so you should be using classes when possible.

Sometimes you aren't able to convert the function to a class for one reason or another.

If that's the case, you can use this hacky solution.

index.ts
function Employee(this: any, fullName: string, salary: number) { this.fullName = fullName; this.salary = salary; this.getSalary = function () { return this.salary; }; } // ✅ No type checker errors const emp1 = new (Employee as any)('James Doe', 100); console.log(emp1.fullName); // 👉️ "James Doe" console.log(emp1.getSalary()); // 👉️ 100

The firs thing we did is type the this keyword in the Employee function - explicitly setting it to any.

This way we won't get an error when setting properties and methods on this.

We used a type assertion to type the Employee function as any right before using the new keyword.

This gets the type checker to comply, but doesn't look great, so it should only be used when you can't convert the constructor function to a class.

In modern code you rarely see constructor functions, as classes are often more intuitive to work with and get better type support.

Use the search field on my Home Page to filter through my more than 1,000 articles.