Typescript

How To Add Multiple Constructors In TypeScript?

If you come from a C# background, you may want to add multiple constructors to a TypeScript class. Although TypeScript doesn’t support multiple...

Written by Luci · 2 min read >

If you come from a C# background, you may want to add multiple constructors to a TypeScript class. Although TypeScript doesn’t support multiple constructors, you can still achieve similar behaviour.

In TypeScript, you can achieve a similar behavior to adding multiple constructors by:

  • Adding constructor overloads AND implementing a custom type guard.
  • Using the static factory method to construct a class.
  • Adding aย partialย class argument to theย constructor.

This article explains those solutions with code examples.

Let’s get to it ๐Ÿ˜Ž.

In TypeScript, unlike other languages, you cannot define multiple constructors inside a class. However, you can achieve similar behaviour by using one of those alternative methods.

How to implement constructor overloads?

One way to simulate adding multiple constructors involves:

  1. Defining multiple constructor overloads inside a class.
  2. Adding the primary constructor implementation, so it supports the other constructor overloads.
  3. Checking the passed arguments with a custom type guard.

Here is an example:

class MyClass {
    private p1: string;
    private p2: number = 0;
    
    constructor(p1: string);
    constructor(p1: string, p2?: number) {
        this.p1 = p1;

        if (p2) {
            this.p2 = p2;
        }
    }
}

const cls1 = new MyClass('Mike');
const cls2 = new MyClass('Mike', 37);

As you can see, in this example, we declare one constructor overload and make the constructor implementation compatible with it.

And this is a more complex example with three constructor overloads:

class MyClass {

    public constructor(p1: number);
    public constructor(p1: string, p2: string);
    public constructor(p1: number, p2: string, p3: string);

    public constructor(...arr: any[]) {
        if (arr.length === 2) {
            console.log('two arguments constructor called.');
        } else if (arr.length === 3) {
            console.log('three arguments constructor called.');
        } else if (arr.length === 1) {
            console.log('one argument constructor called.');
        }
    }

}

As you can see, using constructor overloads in TypeScript can quickly become hard to manage and understand. That’s why I prefer the following method better.

How to use the factory method to construct a class?

The factory method to simulate multiple constructors is much simpler in TypeScript. It involves adding static factory functions to the class that will instantiate it with the correct arguments.

Here is an example:

class MyClass {

    public p1: string = '';
    public p2: number = 0;
    
    public static fromOneValue(p1: string): MyClass {
        const cls = new MyClass();
        cls.p1 = p1;
        return cls;
    }

    public static fromTwoValues(p1: string, p2: number): MyClass {
        const cls = new MyClass();
        cls.p1 = p1;
        cls.p2 = p2;
        return cls;
    }

}

const cls1 = MyClass.fromOneValue('Mike');
const cls2 = MyClass.fromTwoValues('Mike', 27);

In this example, instead of adding constructor overloads, we add two static factory functions that populate a new class instance with the correct arguments and return it.

This method is much simpler to comprehend and maintain.

How to add a partial class argument to the constructor?

Finally, you can pass aย partialย class as the constructor’s argument. That way, you can pass any argument you want to the class.

Here is an example:

class MyClass {
    
    private p1: string = '';
    private p2: number = 0;
    
    constructor(params: Partial<MyClass>) {
        Object.assign(this, params);
    }

}

const cls1 = new MyClass({ p1: 'Tim' });
const cls2 = new MyClass({ p1: 'Tim', p2: 27 });

As you can see, we can pass any class-defined argument to the constructor.

The disadvantage of this method is that since you can pass any argument you want, you can omit a required parameter.

Final thoughts

As you can see, it is easy to simulate multiple constructors in TypeScript.

As for myself, most of the time, I use the factory or the partial argument class method.

Written by Luci
I am a multidisciplinary designer and developer with a main focus on Digital Design and Branding, located in Cluj Napoca, Romania. Profile

How To Create A Queue In TypeScript?

Luci in Typescript
  ·   1 min read
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x