Last updated: Feb 27, 2024
Reading timeยท2 min
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.
new
keyword. If you aren't trying to create an instance of something, you shouldn't use the new
keyword.Here is an example of how the error occurs.
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 which caused the error.
TypeScript wants us to convert the constructor function to a class for better type safety.
To solve the error in this situation, convert the constructor function to a class.
class Employee { constructor( public fullName: string, public salary: number, ) { this.fullName = fullName; this.salary = salary; } getSalary() { return this.salary; } } const emp1 = new Employee('Bobby Hadz', 100); console.log(emp1.fullName); // ๐๏ธ "Bobby Hadz" console.log(emp1.getSalary()); // ๐๏ธ 100
This class creates equivalent objects to the constructor function but allows us
to use the new
keyword to create instances.
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.
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)('Bobby Hadz', 100); console.log(emp1.fullName); // ๐๏ธ "Bobby Hadz" console.log(emp1.getSalary()); // ๐๏ธ 100
The first thing we did was 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.
In modern code, you rarely see constructor functions because classes are often more intuitive to work with and get better type safety.
You can learn more about the related topics by checking out the following tutorials: