Top community members
All Wiki Articles Create Wiki Article

In the past we had a dream,
to have place where we could share IT knowledge,
to ask questions without fear that someone will judge us.

Now we are a group of people who make this dream come true. ❤ 💻

If you think sharing knowledge and helping other is valuable.

join our community - Click here

TypeScript - constructor overloads / multiple constructors / many constructors

0 contributions
5 points

In this article, we're going to have a look at how to overload constructor in TypeScript. In TypeScript constructor oveloading looks different way than in C++, Java or C#. Main idea to overload constructor is to create common constructor that checks what king of parameters was used and later do some logic in case. Useful is to add constructors definitions to help other programmers to know how to use class in proper way.

Simple overview:

class MyClassName {

    public constructor(a : number);
    public constructor(a : number, b : number);
    public constructor(array : Array<number>);

    public constructor(...args : Array<any>) { // common constructor

        // checking arguments and executing proper scenario
        // or throw new Error('Constructor not supported!');
    }
}

// MyClassName usage here...

Check below practical example:

1. Multiple construcotors practical example

Constructor overloading requires to write some logic to detect which constructor has been used. public constructor(...args : Array<any>) contans common logic where depending of used arguments special case of object creating should be used.

class Point {
    private coordinates : Array<number>;

    public constructor(x : number, y : number);
    public constructor(x : number, y : number, z : number);
    public constructor(x : number, y : number, z : number, ...coordinates : Array<number>);
    public constructor(coordinates : Array<number>);

    public constructor(...args : Array<any>) { // common logic constructor
        if(args.length == 0)
            throw new Error('Arguments are not defined.');
    
        let arg = args[0];

        if(Array.isArray(arg)) {
            if(arg.length < 2)
                throw new Error('Minimum number of dimmensions is 2.');
        
            this.coordinates = arg;
        } else
            this.coordinates = args;
    }

    public getCoordinate(dimmension : number) : number {
        return this.coordinates[dimmension];
    }

    public toString() : string {
        let result = '{';

        if(this.coordinates.length > 0) {
            result += ' ' + this.coordinates[0];

            for(let i = 1; i < this.coordinates.length; ++i)
                result += ', ' + this.coordinates[i];
        }

        return result + ' }';
    }
}

let a = new Point(1, 2);
let b = new Point(1, 2, 3);
let c = new Point(1, 2, 3, 4);
let d = new Point([1, 2]);
let e = new Point([1, 2, 3]);
let f = new Point([1, 2, 3, 4]);

console.log(a.toString());
console.log(b.toString());
console.log(c.toString());
console.log(d.toString());
console.log(e.toString());
console.log(f.toString());

Output:

{ 1, 2 }
{ 1, 2, 3 }
{ 1, 2, 3, 4 }
{ 1, 2 }
{ 1, 2, 3 }
{ 1, 2, 3, 4 }

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

2. References

  1. Methods Overloading - Microsoft Docs
0 contributions

Suggested wiki articles:

Suggested findings

Let's do the work and have some fun
  • Dirask is online IT community for professionals and hobbyist to share their knowledge and help each other in extraordinary easy way. ❤ 💻 🙂
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    we will help you. 👍 ✔ 🦄
Read more