3
私の1つのプロジェクトでTypescriptデコレータを使用しようとしていますが、私は理解できない奇妙な動作に遭遇しました。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);
};
}
そして両方がPRINされています
var Test = (function() {
function Test() {
}
__decorate([
TestDecorator('some value'),
__metadata("design:type", String)
], Test.prototype, "property", void 0);
return Test;
}());
そして、ここで、それは私のtsconfig.json
です:コンソールへティン...また
は、両方で、私は同じように正しくかつ正確に装飾されたプロパティを参照することができ、コードをtranspiled。私は(es5
、emitDecoratorMetadata
とexperimentalDecorators
)が正しいと信じて:
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"declaration": true,
"outDir": "dist",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": true
},
"exclude": [
"node_modules",
"dist"
]
}
私は何をしないのですか?同じ問題を持つ人のために