a blog for those who code

Wednesday, 20 May 2015

Get and Set Property in TypeScript

In this post we are going to discuss about Get and Set property in TypeScript. In our previous posts we have discussed about Classes in TypeScript and Functions in TypeScript, in this post we will continue our discussion on TypeScript with Get and Set property.

Get and Set Properties are actually called Accessors. Accessors of a property contains executable statements associated with getting (reading) or setting (writing) the property. The declarations can contain get accessor or set accessor or both.

Example : Use of Get and Set in TypeScript

class Test {
    private _testField: string = null;
    get fieldName() : string {
        return this._testField;
    }
    set fieldName(name : string) {
        this._testField = name;
    }
}

The benefit of using accessors are that you can get the private field or set it without exposing it to the real world. To get and set the property you will write the below lines of code.

var test = new Test();
test.fieldName = "Hello World";
alert(test.fieldName);

In the JavaScript the above Get and Set code will look like :

var Test = (function () {
    function Test() {
        this._testField = null;
    }
    Object.defineProperty(Test.prototype, "fieldName", {
        get: function () {
            return this._testField;
        },
        set: function (name) {
            this._testField = name;
        },
        enumerable: true,
        configurable: true
    });
    return Test;
})();
However you must make sure that the TypeScript compiler targets ECMAScript5 or more.
Please Like and Share the Blog, if you find it interesting and helpful.

No comments:

Post a Comment