Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to customize properties in TypeScript

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

Object.defineProperties(this, {
    view: {
        value: view,
        enumerable: false,
        writable: false,
        configurable: false
    },
});
like image 934
Spongman Avatar asked Oct 02 '12 18:10

Spongman


People also ask

How do I create a properties in TypeScript?

To add a property to an object in TypeScript, set the property as optional on the interface you assign to the object using a question mark. You can then add the property at a later point in time without getting a type error.

What does ?: Mean in TypeScript?

What does ?: mean in TypeScript? Using a question mark followed by a colon ( ?: ) means a property is optional. That said, a property can either have a value based on the type defined or its value can be undefined .

How do you set a property of an object?

After you have created an object, you can set or change its properties by calling the property directly with the dot operator (if the object inherits from IDL_Object) or by calling the object's SetProperty method.


1 Answers

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.

like image 60
Fenton Avatar answered Sep 26 '22 02:09

Fenton