【问题标题】:Typescript decorator only works within the same methodTypescript 装饰器只能在相同的方法中工作
【发布时间】:2017-07-26 17:05:51
【问题描述】:

我正在尝试在我的一个项目中使用 Typescript 装饰器,但遇到了一种我无法理解的奇怪行为。

只有当装饰类位于尝试获取元数据的同一方法中时,它似乎才有效:

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
    });

});

但是一旦我将它移到方法之外,它就不再起作用了:

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
    });

});

两个测试都使用这个测试装饰器:

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

两者都打印到控制台...

另外,在两个转译的代码中,我可以看到属性被正确且完全相同地装饰:

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

这是我的tsconfig.json。我认为是正确的(es5emitDecoratorMetadataexperimentalDecorators):

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

我错过了什么?

【问题讨论】:

    标签: javascript typescript decorator reflect-metadata


    【解决方案1】:

    对于那些有同样问题的人,我不认为这是一个解决方案,但就我而言,从 Webpack 切换到 Rollup.js 解决了问题......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-27
      • 1970-01-01
      • 2019-05-19
      • 1970-01-01
      • 2018-06-08
      • 2023-01-04
      • 2019-11-12
      • 2019-11-27
      相关资源
      最近更新 更多