How to customize properties in TypeScript

后端 未结 3 1067
面向向阳花
面向向阳花 2021-02-02 14:42

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

Object.defineProperties(this, {
    view: {
        value: view,
        enumerable: false,
                


        
3条回答
  •  無奈伤痛
    2021-02-02 15:24

    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.

提交回复
热议问题