How to customize properties in TypeScript

Spongman picture Spongman · Oct 2, 2012 · Viewed 17.3k times · Source

How do I get TypeScript to emit property definitions such as:

Object.defineProperties(this, {
    view: {
        value: view,
        enumerable: false,
        writable: false,
        configurable: false
    },
});

Answer

Fenton picture Fenton · Oct 4, 2012

You can use get and set in TypeScript, which compile into Object.defineProperties.

This is an ECMAScript 5 feature, so you can't use it if you are targeting ES3 (the default for the compiler). If you are happy to target ES5, add --target ES5 to your command.

TypeScript:

class MyClass {
    private view;
    get View() { return this.view; }
    set View(value) { this.view = value }
}

Compiles to:

var MyClass = (function () {
    function MyClass() { }
    Object.defineProperty(MyClass.prototype, "View", {
        get: function () {
            return this.view;
        },
        set: function (value) {
            this.view = value;
        },
        enumerable: true,
        configurable: true
    });
    return MyClass;
})();

But if you want full control of setting enumerable and configurable - you could still use the raw Object.defineProperties code.