如何在TypeScript中自定义属性

Spo*_*man 14 defineproperty typescript

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

Object.defineProperties(this, {
    view: {
        value: view,
        enumerable: false,
        writable: false,
        configurable: false
    },
});
Run Code Online (Sandbox Code Playgroud)

Fen*_*ton 9

您可以在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 }
}
Run Code Online (Sandbox Code Playgroud)

编译为:

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;
})();
Run Code Online (Sandbox Code Playgroud)

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


gaa*_*gaa 8

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

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

他们像这样使用它:

class Greeter {
    greeting: string;
    constructor(message: string) {
        this.greeting = message;
    }

    @enumerable(false)
    greet() {
        return "Hello, " + this.greeting;
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,解决它的另一种方法是使用装饰器.

PS: 此功能需要experimentalDecorators传递tsc或设置标志tsconfig.json.