How to customize properties in TypeScript

后端 未结 3 1022
面向向阳花
面向向阳花 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:43

    I was looking for exactly the same thing when I stumbled upon TypeScript Handbook: Decorators. In "Method Decorators" paragraph they define @enumerable decorator factory, which looks like this (I'm simply copy-pasting from there):

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

    and they use it like this:

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

    So another way of addressing it, is through usage of decorators.

    PS: This feature requires experimentalDecorators flag to be passed to tscor set in tsconfig.json.

提交回复
热议问题