typescript getter / setter重载

时间:2016-01-04 11:16:28

标签: typescript overloading getter-setter

有没有办法重载一个打字稿getter / setter?

我知道打字稿提供了function overloading所以我想出了类似的东西:

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;
    } 
}

但不幸的是,这不起作用=)

1 个答案:

答案 0 :(得分:7)

你的意思是这样吗?

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]