EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials TypeScript Tutorial TypeScript Multiple Constructors
Secondary Sidebar
TypeScript Tutorial
  • TypeScript Basic and Advanced
    • What is TypeScript?
    • Typescript Examples
    • TypeScript Versions
    • TypeScript Operators
    • JavaScript dump object
    • JavaScript get Method
    • Webpack ReactJS
    • Code Generator JavaScript
    • JavaScript Projects
    • Call Stack JavaScript
    • JavaScript Projects GitHub
    • JavaScript Filter Function
    • JavaScript nan
    • JavaScripttimestamp
    • TypeScript loop
    • CoffeeScript
    • TypeScript Webpack
    • setTimeout TypeScript
    • DHTMLX
    • CoffeeScript for loop
    • TypeScript number
    • JavaScript export module
    • TypeScript string contains
    • TypeScript Inheritance
    • TypeScript get
    • TypeScript undefined
    • TypeScript Global Variable
    • TypeScript Dictionary
    • TypeScript Generic
    • TypeScript Cast Object
    • TypeScript Optional Parameters
    • TypeScript? switch
    • TypeScript promise
    • TypeScript tuple
    • TypeScript Hashmap
    • TypeScript let
    • TypeScript Getter
    • TypeScript Pattern Matching
    • TypeScript number to string
    • TypeScript substring
    • TypeScript?lambda
    • TypeScript UUID
    • TypeScript JSDoc
    • TypeScript Decorators
    • Typescript for loop
    • TypeScript HTTP Request
    • TypeScript Abstract Class
    • TypeScript Question Mark
    • TypeScript Nullable
    • TypeScript reduce
    • TypeScript Mixins
    • TypeScript keyof
    • TypeScript string to number
    • TypeScript JSON parse
    • TypeScript const
    • TypeScript declare module
    • TypeScript String
    • TypeScript filter
    • TypeScript Multiple Constructors
    • TypeScript? Set
    • TypeScript string interpolation
    • TypeScript instanceof
    • TypeScript JSON
    • TypeScript Arrow Function
    • TypeScript generator
    • TypeScript namespace
    • TypeScript default parameter
    • TypeScript cast
    • TypeScript babel
    • Typescript Key-Value Pair
    • TypeScript if
    • TypeScript keyof Enum
    • TypeScript wait
    • TypeScript Optional Chaining
    • TypeScript JSX
    • TypeScript Version Check
    • TypeScript Unit Testing
    • TypeScript Handbook
    • TypeScript module
    • TypeScript Extend Interface
    • TypeScript npm
    • TypeScript pick
    • TypeScript Interface Default Value
    • JavaScript import module
    • Obfuscate Javascript
    • TypeScript basics
    • setInterval TypeScript
  • Type of Union
    • TypeScript Object Type
    • TypeScript type check
    • TypeScript promise type
    • TypeScript JSON type
    • TypeScript Union Types
    • TypeScript typeof
    • TypeScript Types
  • TypeScript Array
    • TypeScript Array of Objects
    • Methods TypeScript Array
    • TypeScript remove item from array
    • TypeScript add to array
    • TypeScript Array Contains
  • Function Of Array
    • TypeScript Function Interface
    • TypeScript Functions
    • TypeScript Export Function
    • TypeScript function return type

TypeScript Multiple Constructors

By Shalu SharmaShalu Sharma

TypeScript Multiple Constructors

Definition of TypeScript Multiple Constructors

In TypeScript, we cannot define multiple constructors like other programming languages because it does not support multiple constructors. But, we have some alternatives which can be used to define multiple constructors in TypeScript, but there is no direct way to direct multiple constructors as we do in Java, c++, and other object-oriented programming languages. To implement this we have to give a common implementation for all constructors we have defined in a TypeScript class. In the coming section, we will discuss in more detail about implementation to make use of it while application development.

Syntax:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

As discussed we have to give a common implementation of all constructors in order to have multiple constructors support in TypeScript. Let’s see its syntax for a better understanding of its usage see below;

public constructor(...args: any[]) {
// your logic will go here ..
}

In the above lines of code as you can see we are just using the ‘constructor’ keyword to define a constructor implementation. Inside this, we are taking arguments array. Let’s see one practice syntax for multiple constructor support in TypeScript for better understanding see below;

e.g. :

public constructor(...args: any[]) {
if (args.length === your value) {
// logic for your called constructor goes here..
}
}

As you can see we are checking the number of the argument here to check which constructor is being called. In the coming section, we will discuss more its internal working and how we can write and use the logic for this constructor to make our code efficient.

How to work with Multiple constructors?

As we already know that we have use constructors implementation to give support for multiple constructors in TypeScript. But there is no direct way to implement them easily we have to use some alternative ways in TypeScript. We can define a number of constructors in our class but we have to give one common implementation for all the constructors defined inside this constructor we can write our own logic in TypeScript. In this section we will discuss more its internal working with a sample piece of code for beginners, Let’s get started to see below;

constructors implementation: This is used to give implementation for all the constructors defined in the TypeScript class. We can individually check the argument or else we can define constructors that accept any argument array and then we can the length of it. Let’s take a simple example for better understanding see below;

e.g. :

class DemoClassTest {
public constructor(x : string, y:string);
public constructor(x : number);
public constructor(x : number, y:string, z:string);
public constructor(...myarray: any[]) {
if (myarray.length === 2) {
console.log('two argument constructor called here !!');
return;
}
if (myarray.length === 3) {
console.log('three argument constructor called here !!');
return;
}
if (myarray.length === 1) {
console.log('one argument constructor called here !!');
return;
}
}
}
let a = new DemoClassTest('hello', 'bye');
let b = new DemoClassTest(1);
let c = new DemoClassTest(100, 'str1', 'str2');

As you can see in the above example we have defined so many constructors inside the class which accept a different parameter of a different type. We have defined one constructor which accepts argument array, inside this, we are changing how many arguments is being passed while creating the instance for the class, then we can apply the logic we want to execute in TypeScript. Also at last we are creating a different object to invoke the constructor of a different type. first, we have created object ‘a’ which accepts string and string. The second one called as ‘b’ which accepts only one parameter as a number type. The third parameter is ‘c’ which accept the three-parameter number, string and string according to the passing argument the logic inside the implemented constructor will be executed.

Examples

In this example we are trying to implement multiple constructor support , this is a simple example for beginners to understand the concept of multiple constructors in Typescript in detail.

Code:

class DemoClassTest {
public constructor(x : string, y:string);
public constructor(x : number);
public constructor(x : number, y:string, z:string);
public constructor(...myarray: any[]) {
if (myarray.length === 2) {
console.log("arugument length is :: " + myarray.length)
console.log('two argument constructor called here !!');
return;
}
if (myarray.length === 3) {
console.log("arugument length is :: " + myarray.length)
console.log('three argument constructor called here !!');
return;
}
if (myarray.length === 1) {
console.log("arugument length is :: " + myarray.length)
console.log('one argument constructor called here !!');
return;
}
}
}
console.log("Example to show multiple constructor support in Typescript !!")
let result1 = new DemoClassTest('hello', 'bye');
let result2 = new DemoClassTest(1);
let result3 = new DemoClassTest(100, 'str1', 'str2');
console.log("Printing result here !!")
console.log( "result one is :::" + result1)
console.log("result two is :::" +result2)
console.log("result three is :::" +result3)

Output:

TypeScript Multiple Constructors

Rules and Regulations for multiple constructors

There are some rules that we need to follow while implementing multiple constructors in TypeScript which are a follows see below;

1) First thing to keep in mind that TypeScript does not support the implementation of multiple constructors directly. We have to use alternative ways to support multiple constructors.

2) If you have defined multiple constructors in the TypeScript class then we have to define a common implementation of all the constructors that we have already discussed.

3) If we have a constructor which accepts a same number of the argument but different type then additionally we have to apply the condition to check the type of passed argument as well.

4) if we do not provide an implementation of constructor inside the multiple constructor TypeScript class then it will throw a runtime exception.

5) Multiple constructors in Typescript if not correctly implement may throw exceptions, we can implement any number of constructors inside our Typescript class.

Conclusion

TypeScript support multiple constructors by providing the implementation of a constructor. There is no simple and direct way to implement this. In this article, we have already discussed the ways to support multiple constructors in TypeScript. This will make the application code efficient and reusable with some logic.

Recommended Articles

We hope that this EDUCBA information on “TypeScript Multiple Constructors” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

  1. TypeScript let
  2. TypeScript typeof
  3. TypeScript Cast Object
  4. TypeScript Dictionary
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2023 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more