【发布时间】:2021-09-30 03:13:39
【问题描述】:
我可以使用reflect-metadata 创建自定义装饰器,它工作正常。
问题是,我不知道如何获取所有实例装饰器。
import 'reflect-metadata';
console.clear();
function readTypes() {
const decorator: MethodDecorator = (target, propertyKey, description) => {
const args = Reflect.getMetadata(
'design:paramtypes',
target,
propertyKey
).map(c => c.name);
const ret = Reflect.getMetadata('design:returntype', target, propertyKey);
console.log(`Arguments type: ${args.join(', ')}.`);
console.log(`Return type: ${ret.name}.`);
};
return decorator;
}
class Foo {}
class Bar {
@readTypes()
public fn(a: number, b: string, c: Foo): boolean {
return true;
}
}
const barInstance = new Bar();
我想从barInstance 获取所有带有装饰器@readTypes 的函数。我该怎么做?
查看工作示例: https://stackblitz.com/edit/decorators-metadata-example-nakg4c
【问题讨论】:
标签: javascript typescript decorator reflect-metadata