I'm working on a creating a TypeScript library that will be used across multiple frameworks including Vue, Angular, React, and Svelte. It is an interesting challenge. Along the way I discovered that Typescript supports constructor overloading. This means we can create a class with multiple constructors, each having a different signature.

Let's start with a simple class:

view plain print about
1export class MyClass {
2
3 constructor() {}
4
5}

That is one constructor, with no arguments that does nothing. A cool thing, though, is we can provide options:

view plain print about
1export class MyClass {
2
3 constructor();
4 constructor(myValue: string);
5 constructor(myValue?: string){
6 if (myValue) {
7 // process value
8 }
9 }
10
11}

First, we display the constructor method signatures. In this case I have two:

view plain print about
1constructor();
2 constructor(myValue: string);

Then we have an implementation of the constructor:

view plain print about
1constructor(myValue?: string){
2 if (myValue) {
3 // process value
4 }
5 }

The signature has required arguments, but the constructor implementation uses optional arguments for the input.

We can create an instance of the class passing in the value:

view plain print about
1const value = new MyClass('foobar');

Or not:

view plain print about
1const value = new MyClass();

And both approaches work, giving me a new instance of the class.