Lambert Lambert - 3 months ago 10
TypeScript Question

Is there a way to use the same name for both a setter method and class property?

In a typescript class, is there a way to use the same name for both a setter method and class property? This would make setting and getting values more consistent. For example:

myClass.myValue = "Hello"; //Setter.
var myValue = myClass.myValue; //Getter.

class myClass {
myValue: string;

myValue(inArg: string) {
alert("inArg: " + inArg);
}
}

Answer

No, and that has to do with how the class is created in javascript:

var MyClass = (function () {
    function MyClass() {
        this.myValue = "string";
    }
    MyClass.prototype.myValue = function (inArg) {
        alert("inArg: " + inArg);
    };
    return MyClass;
}());

When you then do:

let obj = new MyClass();

You create an instance of the class which has everything that exist in the prototype, including the myValue method, but then in the constructor you override the property myValue with a string.

It's similar to doing this:

class MyClass {
    myValue(inArg: string) {
      alert("inArg: " + inArg);
   }
}

let obj = new MyClass();
obj.myValue = "a string";

The only difference being that in this example you override myValue only for obj but not other instances of MyClass, whereas in your example it will do it for all instances because it's in the constructor.