import 'reflect-metadata';
// 定义属性装饰器
function metadataDecorator(key: string, value: any) {
return function (target: Object, propertyKey: string | symbol) {
Reflect.defineMetadata(key, value, target, propertyKey);
};
}
// 使用装饰器的类
class MyClass {
@metadataDecorator('description', 'This is a sample property')
myProperty: string;
constructor() {
this.myProperty = 'Hello, TypeScript';
}
}
// 获取元数据的逻辑
const instance = new MyClass();
const metadataValue = Reflect.getMetadata('description', instance, 'myProperty');
console.log(metadataValue);
- 首先,引入
reflect - metadata
库,这是在TypeScript中处理元数据所必需的。
- 定义
metadataDecorator
属性装饰器,它接受两个参数key
和value
,并使用Reflect.defineMetadata
来为类的属性添加元数据。
- 在
MyClass
类中,对myProperty
属性应用metadataDecorator
装饰器。
- 创建
MyClass
的实例,并使用Reflect.getMetadata
来获取之前添加的元数据。