【问题标题】:How to customize properties in TypeScript如何在 TypeScript 中自定义属性
【发布时间】:2012-10-02 18:40:59
【问题描述】:

如何让 TypeScript 发出属性定义,例如:

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

【问题讨论】:

    标签: typescript defineproperty


    【解决方案1】:

    您可以在 TypeScript 中使用getset,它们会编译成Object.defineProperties

    这是 ECMAScript 5 的一项功能,因此如果您的目标是 ES3(编译器的默认设置),则不能使用它。如果您愿意以 ES5 为目标,请将 --target ES5 添加到您的命令中。

    打字稿:

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

    编译为:

    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;
    })();
    

    但如果您想完全控制设置可枚举和可配置 - 您仍然可以使用原始 Object.defineProperties 代码。

    【讨论】:

    • 好的...但是你如何处理类似的事情:describe('MyComponent', () => { beforeAll(() => { Object.defineProperty(window, 'matchMedia', { value: jest.fn(() => { return {matches: true}; }) }); }); });
    【解决方案2】:

    当我偶然发现TypeScript Handbook: Decorators 时,我正在寻找完全相同的东西。在“方法装饰器”段落中,他们定义了 @enumerable 装饰器工厂,看起来像这样(我只是从那里复制粘贴):

    function enumerable(value: boolean) {
        return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
            descriptor.enumerable = value;
        };
    }
    

    他们这样使用它:

    class Greeter {
        greeting: string;
        constructor(message: string) {
            this.greeting = message;
        }
    
        @enumerable(false)
        greet() {
            return "Hello, " + this.greeting;
        }
    }
    

    所以另一种解决方法是使用装饰器。

    PS: 此功能需要将experimentalDecorators 标志传递给tsc 或在tsconfig.json 中设置。

    【讨论】:

      【解决方案3】:

      如果您希望所有属性都像这样发出,则目前不支持此功能。我建议在CodePlex site 提交问题,详细说明您的用例和要求。

      如果你用 --target ES5 编译,你可以有这样的东西:

      class n {
          get foo() { return 3; }
          bar() { return 5; }
      }
      

      生成此代码:

      var n = (function () {
          function n() { }
          Object.defineProperty(n.prototype, "foo", {
              get: function () {
                  return 3;
              },
              enumerable: true,
              configurable: true
          });
          n.prototype.bar = function () {
              return 5;
          };
          return n;
      })();
      

      【讨论】:

      • 是的,我正在寻找一种方法来自定义“可枚举”、“可配置”和“可写”属性以匹配我现有的代码。
      猜你喜欢
      • 1970-01-01
      • 2019-07-19
      • 2018-07-26
      • 1970-01-01
      • 2012-12-06
      • 2018-07-20
      • 2022-11-21
      • 1970-01-01
      相关资源
      最近更新 更多