MuriloKunze MuriloKunze - 3 months ago 10
TypeScript Question

get and set in TypeScript

I'm trying to create get and set method for a property:

private _name: string;

Name() {
get:
{
return this._name;
}
set:
{
this._name = ???;
}
}


What's the keyword to set a value?

Answer

Typescript uses getter/setter syntax that is like ActionScript3.

class foo {
    private _bar:Boolean = false;
    get bar():Boolean {
        return this._bar;
    }
    set bar(theBar:Boolean) {
        this._bar = theBar;
    }
}

That will produce this Javascript, using the Ecmascript 5 Object.defineProperty() feature.

var foo = (function () {
    function foo() {
        this._bar = false;
    }
    Object.defineProperty(foo.prototype, "bar", {
        get: function () {
            return this._bar;
        },
        set: function (theBar) {
            this._bar = theBar;
        },
        enumerable: true,
        configurable: true
    });
    return foo;
})();

So to use it,

var myFoo = new foo();
if(myFoo.bar) {         // calls the getter
    myFoo.bar = false;  // calls the setter and passes false
}

However, in order to use it at all, you must make sure the TypeScript compiler targets ECMAScript5. If you are running the command line compiler, use --target flag like this;

tsc --target ES5

If you are using Visual Studio, you must edit your project file to add the flag to the configuration for the TypeScriptCompile build tool. You can see that here:

Comments