TypeScript Getters Setters with TypeScript Accessor Tutorial

Update: New and better Boilerplate that uses ES6 Modules in TypeScript check it out.

In this TypeScript tutorial I will be going over TypeScript Getters and Setters which are called TypeScript Accessor.

To get TypeScript Accessor’s working we need to let the compiler know we want to export the code as ECMAScript 5 compliant. Below is the TypeScript command:

 
tsc --target ES5 example.ts

Below you will notice that there are two methods named “name”. Notice the “get” and “set” in front of the methods. You don’t need to put the “public” in front of the “get” and “set” but I think it looks better.

 
class Person {

    private _name:string = null;

    constructor() {

    }

    public get name():string
    {
        return "The person name is " + this._name;
    }

    public set name(value:string)
    {
        this._name = value;
    }

}

On a side note, you will get a compiler error if you put a return type of :void on the set method. I think putting :void as the return type would and should be ok.

In our Main.ts class you can see how we set and get the data for the Person.ts class.

 
///<reference path='Person.ts'/>

class Main {

    private _personOne:Person = null;
    private _personTwo:Person = null;

    constructor()
    {
        this._personOne = new Person();
        this._personOne.name = "Tim";

        this._personTwo = new Person();
        this._personTwo.name = "Mark";

        console.log(this._personOne.name);
        console.log(this._personTwo.name);
    }

}

Like I said above we need to compile this out as ECMAScript 5 compliant or the compiler will complain. Here is our TypeScript compiler command.

 
tsc --target ES5 Main.ts -out ../../deploy/app.js

Below you will see the exported code for the Person.ts class. Notice the Object.defineProperty and that is how we can have getters and setters in JavaScript.

 
var Person = (function () {
    function Person() {
        this._name = null;
    }
    Object.defineProperty(Person.prototype, "name", {
        get: function () {
            return "The person name is " + this._name;
        },
        set: function (value) {
            this._name = value;
        },
        enumerable: true,
        configurable: true
    });
    return Person;
})();

You can check what browsers support Object.defineProperty here: http://kangax.github.com/es5-compat-table/.

Below you can download the TypeScript tutorial example files. Also if you like this tutorial please provide a link back to this page or my site.

Leave a Reply