Categories
TypeScript Answers

How to add constructor overload with empty constructor in TypeScript?

Spread the love

Sometimes, we want to add constructor overload with empty constructor in TypeScript.

In this article, we’ll look at how to add constructor overload with empty constructor in TypeScript.

How to add constructor overload with empty constructor in TypeScript?

To add constructor overload with empty constructor in TypeScript, we can add different signatures for constructor in our class.

For instance, we write

class Foo {
  constructor();
  constructor(id: number);
  constructor(id: number, name: string, surname: string, email: string);
  constructor(id?: number, name?: string, surname?: string, email?: string) {
    this.id = id;
    this.name = name;
    this.surname = surname;
    this.email = email;
  }
}

to overload constructor by adding different signatures for it.

Then we can do whatever we want with the parameters listed in any signature in the constructor body.

Conclusion

To add constructor overload with empty constructor in TypeScript, we can add different signatures for constructor in our class.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *