user378380
user378380

Reputation: 779

method overload not working for me

I want to do simple get/set methods on a private variable so I do

_Var1:number = 0;

Var1():number
{
   return this._Var1;
}

Var1(num:number)
{
   this._Var1 = num;
}

This throws a compiler error. Can a method that takes no arguments and a method that takes one argument share the same name?

Upvotes: 0

Views: 4104

Answers (3)

basarat
basarat

Reputation: 276229

Here you go

    Var1(input?:number):number
    {
        if(typeof input != typeof 123)
            return this._Var1;
        else
            return this._Var1 = input;
    }

However if you are curious about the overload signatures, you would need to do something like this:

class Foo{

    _Var1:number = 0;

    // Sample of overload signatures
    Var1():number
    Var1(input:number):number
    Var1(input?:any):number // The last signature Must be super set of all previous signatures. 
    {
        if(typeof input != typeof 123)
            return this._Var1;
        else
            return this._Var1 = input;
    }
}

More

Docs on function overloading : https://basarat.gitbooks.io/typescript/content/docs/types/functions.html#overloading

Upvotes: 4

Stephen Chung
Stephen Chung

Reputation: 14605

You need a generic implementation for function overloads:

Var1(): number;
Var1(num: number): void;
Var1(num?: number): any
{
    if (num === undefined) return this._Var1;
    this._Var1 = num;
}

What's overloaded is the function's declaration, not its implementation. The last line: Var1(num?: number): any is the generic function declaration. It is necessary. The lines above it are the overloaded declarations.

Upvotes: 1

Fenton
Fenton

Reputation: 250842

If you are targeting ECMAScript 5 or above, your code just needs the get and set keywords:

_Var1:number = 0;

get Var1():number
{
   return this._Var1;
}

set Var1(num:number)
{
    this._Var1 = num;
}

If you want to target older version, I would recommend using getVar1 and setVar1 method names rather than an overload, which would force you to check the input. The two methods are very concise.

Alternatively, you can take advantage of a neat trick that allows you to use runtime variables as default arguments:

Var1(num: number = this._Var1) {
    return this._Var1 = num;
}

I still prefer methods named get... and set... for the following reasons: the generated JavaScript for this will look heinous because it will contain code that is unnecessary for gets. It also returns a value when you set, which isn't the normal convention.

Upvotes: 1

Related Questions