Languages
[Edit]
EN

TypeScript - constructor overloads / multiple constructors / many constructors

25 points
Created by:
Palus-Bear
1016

In this article, we're going to have a look at how to overload constructor in TypeScript.

Quick solutions:

1. with optional arguments (argName?: TypeHere):

2. using declared overloads and common constructor

3. using multiple types for arguments

 

Practical examples

Edit

1. Problem

Edit

Needed two or more constructors.

2. Solution

Edit

In TypeScript, constructor overloading looks different way than in C++, Java, or C#. The main idea to overload the constructor is to create a common constructor that checks what kind of parameters were passed to create an object and later do some logic for the proper case. Useful is to add constructors' definitions to help other programmers to know how to use class in a proper way.

2.1. Optional argument example

Edit

In this section ? operator was used to create a common constructor.

2.2. Declared overloads and common constructor example

Edit

In this section, we declared overloads with common constructor.

2.3. Multiple types for arguments example

Edit

In this section, we used second argument with two types.

3. More complicated example

Edit

Constructor overloading requires writing some logic to detect, which constructor has been used. public constructor(...args : Array<any>) contains common logic, where depending on used arguments special case of the object creating should be used. Using array in common constructor we are able to use totally different constructors with different types in the same place. 

Output:

Note: big number of overloading can lead to big amount of mistakes so it is better to avoid this technic.

4. References

Edit
  1. Methods Overloading - Microsoft Docs
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

TypeScript

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join