Search code examples
typescriptdefineproperty

How to customize properties in TypeScript


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

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

Solution

  • 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.