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

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.


  1. What's up, this weekend is good in support of me,
    for the reason that this time i am reading this wonderful informative paragraph here
    at my residence.

  2. Hi, i feeel that i notied you visitted my weblog thus i came to return thee
    prefer?.I am attempting to find things to improve my web site!I
    assume its good enough to use a few of your ideas!!

  3. Hey thhere would you mind letting me know which web host you're working with?

    I've loaded your blog in 3 completely different browsers and I must say thhis
    blog loads a lot faster then most. Can you suggest
    a good web hosting provider at a honest price? Kudos, I appreciate it!

  4. whoah this weblog iis wonderful i really like studying yoiur articles.
    Keep up the great work! You know, many individuals are hunting
    round for this info, you can help them greatly.

  5. I have reqd so many articles about the blogger lovers however this paragraph is actrually a good article, keep itt up.

  6. Hurrah! Finally I got a webpage from where I know how to genuinely take helpful data concerning my study and knowledge.