代码之家  ›  专栏  ›  技术社区  ›  Spongman

如何在TypeScript中自定义属性

  •  18
  • Spongman  · 技术社区  · 13 年前

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

    Object.defineProperties(this, {
        view: {
            value: view,
            enumerable: false,
            writable: false,
            configurable: false
        },
    });
    
    3 回复  |  直到 8 年前
        1
  •  11
  •   Fenton    13 年前

    您可以使用 get set 在TypeScript中,编译为 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;
    })();
    

    但是,如果你想完全控制设置可枚举和可配置,你仍然可以使用原始 对象定义属性 密码

        2
  •  9
  •   gaa    9 年前

    我在找完全一样的东西时偶然发现 TypeScript Handbook: Decorators 在“方法修饰者”一段中,他们定义 @enumerable decorator工厂,看起来是这样的(我只是从那里复制粘贴):

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

    因此,解决这个问题的另一种方法是使用装饰器。

    附言: 此功能需要 experimentalDecorators 要传递到的标志 tsc 或设置在 tsconfig.json

        3
  •  1
  •   Ryan Cavanaugh    13 年前

    如果您希望所有属性都像那样发出,则当前不支持这样做。我建议在 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;
    })();