How to use constructor overload in Typescript?

Asked

Viewed 2,573 times

9

In languages with C#, for example, it is possible to use constructor overload as shown below:

    public class Teste{
        public Teste(bool a, int b, string c){ }
        public Teste(bool a, int b){ }
        public Teste(bool a){ }
    }

After some time searching I managed to carry out the constructor overload in Typescript this way:

export class Telefone {
    constructor(a: boolean);
    constructor(a: boolean, b: number);
    constructor(a: boolean, b: number, c: string);
    constructor(public a?: boolean, public b?: number, c?: string){ }
}

Is there another way to accomplish this? This way above does not solve overloads like this:

public Teste(bool a){}
public Teste(int b){}

3 answers

9

This is impossible, because when code is compiled for Javascript there will be two functions with exactly the same signature. Since Javascript does not support typing.

You always need to keep in mind that the Typescript code will compile for Javascript. The only way Javascript has to differentiate overloads is by the amount of parameters.

My tip for you is to change the first parameter to any (anything) and validate within the body of the constructor, is not a great way to work, but is what the language will offer.

constructor(arg: any) {
    if (obj instanceof bool) {

    } else if(obj instanceof number) {
        //faz outra coisa
    }
}

8


Typescript did not solve this problem that already existed in JS. You can fix that, but there must be something that makes it harder, maybe maintain interoperability with pure JS code.

You gotta do it the way you always do it:

class Classe {
    constructor(obj: any) {
        if (obj instanceof Array) {
            //faz algo
        } else {
            //faz outra coisa
        }
    }
}

Behold in the Playground typescript.

Or else:

class Classe {
    constructor(obj: boolean | number) {
        if (typeof obj === "boolean") {
            //faz algo
        } else {
            //faz outra coisa
        }
    }
}

Behold in the Playground typescript.

I put in the Github for future reference.

The normal of Overload Typescript is just making it easy to call a constructor with slightly different constructs, so only the latter can have an implementation. All others must call the single builder.

5

Hello, maybe letting a builder with type any is not so elegant, since Tsc offers us the possibility to use Generics.

Stop this situation that you quoted would work, although it is still limited to just one argument.

public test(bool a){}

public test(int b){}

Ex:

export class Teste<T> {    
  constructor(obj: T){
  }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.