11

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 =)

1 Answer 1

10

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]

Sign up to request clarification or add additional context in comments.

4 Comments

Hi Martin, this is definitely an improvement. But i'd prefer that the protected property and the getter just represent a string. Only the setter should have a number overload. But then i get an error because the getter and setter must have the same type :/
There is a closed issue for this: github.com/Microsoft/TypeScript/issues/2521 (github.com/Microsoft/TypeScript/issues/4087) Unfortunately, the current behavior is by design.
Thx so your solution is the way to go for now. Even if i dont like the fact that a property has multiple types.
@MartyIX as of TypeScript 5.1.0, it is now permitted for the setter and getter to have different types. See github.com/microsoft/TypeScript/issues/43662. Unfortunately setter overloads still do not appear to be supported (see this Playground example).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.