Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typescript getter / setter overload

Is there a way to overload a typescript getter / setter?

I know that typescript provides function overloading so i came up with something like this:

public get stringOrNumber(): string { return this._stringOrNumber; }

public set stringOrNumber(value: number);
public set stringOrNumber(value: string) { 
    if(typeof stringOrNumber == 'number') {
        this._stringOrNumber = value.toString();
    } else {
        this._stringOrNumber = value;
    } 
}

But unfortunately this doesn't work =)

like image 723
pbo Avatar asked Jan 04 '16 11:01

pbo


1 Answers

Do you mean something like this?

class A {

    protected _stringOrNumber: string|number;

    public get stringOrNumber(): string|number { 
        return this._stringOrNumber; 
    }

    public set stringOrNumber(value: string|number) { 
        if(typeof this.stringOrNumber === 'number') {
            this._stringOrNumber = value.toString();
        } else {
            this._stringOrNumber = value;
        } 
    }
}

[Playground]

like image 92
Martin Vseticka Avatar answered Oct 17 '22 14:10

Martin Vseticka