ProgrammingFullstack Developer

How to implement and type overloaded class constructors in TypeScript? Why can't you simply specify multiple constructor methods, and how to achieve this correctly?

Pass interviews with Hintsage AI assistant

Answer.

TypeScript does not support multiple constructor bodies in a single class, as is possible in many OOP languages. Instead, you can declare multiple constructor signatures (overloads), and then implement a single constructor body, where you manually parse the arguments:

class User { name: string; age: number; constructor(name: string); constructor(name: string, age: number); constructor(name: string, age?: number) { this.name = name; this.age = age ?? 18; } } const u1 = new User('Alice'); // age = 18 const u2 = new User('Bob', 32); // age = 32

Important details:

  • You can specify multiple signatures above the implementation in the class, but only ONE constructor implementation is allowed.
  • The constructor implementation must be compatible with all overload variants.
  • TypeScript will automatically check the arguments for overload compatibility.

A trick question.

"Can the constructor be implemented like this?"

undefined

class Test { constructor(x: number) {} constructor(x: string) {} }


**Correct answer:** No, this code will throw an error: "Duplicate constructor implementation". In TypeScript, only one implementation of the constructor body is allowed, and overloads are specified as signatures (without a body).

### Examples of real errors due to lack of knowledge on the topic.

---
> Story

In the project, there was an attempt to implement a class with two constructors with different parameters — copying experience from Java. As a result, TypeScript throws a compilation error, the project does not compile, and it was necessary to urgently refactor to use overloads in signatures.

---
> Story

One team member wrote a class constructor with overloads but forgot to consider the optional nature of parameters (did not handle undefined). This led to attempts to access non-existing values and failures when creating instances with the minimal set of arguments.

---
> Story

Constructor overloads were declared, but the constructor body did not match the described call variants. In one case, a second argument was expected to be mandatory, while in the signature it was optional. Such a conflict was not identified immediately, but it surfaced during unit testing and complicated debugging.