Change property descriptor (enumerable) from within TypeScript decorator

567 views Asked by At

I just wanted to share the results of a brief struggle with TypeScript decorators.

I was trying to do change a property descriptor from within a property decorator, e.g. in order to make a property enumberable:

export function MyPropDecorator<T>(options: {enumerable: boolean, <other options...> }) {
    return function (target: any, key: string): any {
        let type = Reflect.getMetadata("design:type", target, key);
        let pd = Object.getOwnPropertyDescriptor(target, key);
        pd.enumerbale = options.enumerable;
        Object.defineProperty(target, key, pd);
        ...
    }
}

But as soon as the decorator function was left, "eumerable" was somehow changed back to "false". The problem is that one must not call "Object.defineProperty" within a property decorator because the TypeScript "__decorate" function will overwrite it. The trick is to return the modified property descriptor:

export function MyPropDecorator<T>(options: {enumerable: boolean, <other options...> }) {
    return function (target: any, key: string): any {
        let type = Reflect.getMetadata("design:type", target, key);
        let pd = Object.getOwnPropertyDescriptor(target, key);
        pd.enumerbale = options.enumerable;
        return pd;
    }
}
0

There are 0 answers