Typescript decorator only works with the same method

I am trying to use Typescript decorators in the same project, but I am running into strange behavior that I am not able to understand.

It only works if the decorated class is inside the same method that is trying to get the metadata:

describe('metadata tests', () => {

    it('should retrieve metadata', () => {

        class Test {
            @TestDecorator('some value')
            property: string;
        }

        const metadata = Reflect.getMetadata('test', new Test(), 'property');
        expect(metadata).toEqual('some value'); //Passes
    });

});

      

But as soon as I move it outside of the method, it doesn't work anymore:

describe('metadata tests', () => {

    class Test {
        @TestDecorator('some value')
        property: string;
    }

    it('should retrieve metadata', () => {
        const metadata = Reflect.getMetadata('test', new Test(), 'property');
        expect(metadata).toEqual('some value'); //Fails
    });

});

      

Both tests use this decorator:

function TestDecorator(value: any) {
    return function (target: any, propertyKey: string) {
        console.log(`I'm being decorated!`);
        Reflect.defineMetadata('test', value, target, propertyKey);
    };
}

      

And both are printing to the console ...

Also, in both coded codes, I see that the property is styled correctly and exactly the same:

var Test = (function () {
    function Test() {
    }
    __decorate([
        TestDecorator('some value'),
        __metadata("design:type", String)
    ], Test.prototype, "property", void 0);
    return Test;
}());

      

And this is mine tsconfig.json

. I think the correct ( es5

, emitDecoratorMetadata

and experimentalDecorators

):

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es5",
    "declaration": true,
    "outDir": "dist",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": true
  },
  "exclude": [
    "node_modules",
    "dist"
  ]
}

      

What am I missing?

+3


source to share


1 answer


For those with the same problem, I don't think this is a solution, but in my case, switching from Webpack to Rollup.js solved the problem ...



0


source







All Articles