How to use constructor overload in TypeScript?

4

In languages with C #, for example, you can use the builder 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 was able to perform the constructor overload in TypeScript like this:

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 resolve overloads like this:

public Teste(bool a){}
public Teste(int b){}
    
asked by anonymous 11.10.2016 / 19:52

3 answers

4

TypeScript did not solve this problem that was already in JS. You can even work around that, but you should have something that makes it difficult, maybe maintain interoperability with pure JS code.

You have to solve it the way you always did:

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

See #.

Or:

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

See no TypeScript Playground .

The overload of the TypeScript is just to facilitate the call of a constructor with slightly different constructs, so only the latter can have an implementation. All others must call the single constructor.

    
11.10.2016 / 20:11
3

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

You always have to keep in mind that the TypeScript code will compile for JavaScript. The only way JavaScript has to differentiate overloads is by the number of parameters.

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

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

    } else if(obj instanceof number) {
        //faz outra coisa
    }
}
    
11.10.2016 / 20:07
2

Hello, maybe leaving a constructor with type any is not so elegant, since tsc offers us the possibility to use Generics .

Stop this situation you mentioned 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){
  }
}
    
17.10.2016 / 19:56