你能得到關於使用reflect-metadata自定義裝飾數據。通過在裝飾器實現中定義屬性的元數據是可能的 - see on codesandbox。你只能用你卻自定義裝飾第三方庫經常這樣做也用這樣的方式與不同的metadata key
// be sure to import reflect-metadata
// without importing reflect-metadata Reflect.defineMetadata and other will not be defined.
import "reflect-metadata";
function First(target: Object, propertyKey: string | symbol) {
// define metadata with value "First"
Reflect.defineMetadata("custom:anotations:first", "First", target, propertyKey);
}
function Second(target: Object, propertyKey: string | symbol) {
// define metadata with value { second: 2 }
// be sure that metadata key is different from First
Reflect.defineMetadata("custom:anotations:second", { second: 2 }, target, propertyKey);
}
class Test {
@First
@Second
someAttribute: string;
}
// get decorators
function getDecorators(target: any, propertyName: string | symbol): string[] {
// get info about keys that used in current property
const keys: any[] = Reflect.getMetadataKeys(target, propertyName);
const decorators = keys
// filter your custom decorators
.filter(key => key.toString().startsWith("custom:anotations"))
.reduce((values, key) => {
// get metadata value.
const currValues = Reflect.getMetadata(key, target, propertyName);
return values.concat(currValues);
}, []);
return decorators;
}
// test
var t = new Test();
var decorators = getDecorators(t, "someAttribute"); // output is [{ second: 2}, "First"]
console.log(decorators);
不要忘了,爲了能夠與元數據操作添加"emitDecoratorMetadata": true
您tsconfig.json
。
獎勵:執行與class decorators
支持 - see on codesandox
附:這是一個老問題,但是,我希望我的答案能夠幫助某人。