我正在使用带有typescript的reflect-metadata。我编写了自己的属性装饰器,名为Field。如何获取任何类型的字段/属性列表,这些字段/属性由Field修饰。例如:我想从下面的Product/shown类中获取ProductID,ProductName字段及其元数据。
import 'reflect-metadata';
export const FIELD_METADATA_KEY = 'Field';
export interface FieldDecorator {
field?: string;
title?: string;
type?: string;
}
export function Field(field: FieldDecorator) {
return Reflect.metadata(FIELD_METADATA_KEY, field);
}
export class Product {
@Field({
title: 'Product Id'
})
ProductID: string;
@Field({
title: 'Product Name',
type: 'text'
})
ProductName: string;
UnitPrice: number; //not decorated
}发布于 2021-10-28 10:05:41
不幸的是,reflect-metadata api没有公开这一点。
作为一种解决办法,您可以自己存储字段列表:
export const FIELD_METADATA_KEY = 'Field';
export const FIELD_LIST_METADATA_KEY = 'FieldList';
export function Field(field: FieldDecorator) {
return (target: Object, propertyKey: string | symbol) => {
// append propertyKey to field list metadata
Reflect.defineMetadata(FIELD_LIST_METADATA_KEY, [...Reflect.getMetadata(FIELD_LIST_METADATA_KEY, target) ?? [], propertyKey], target);
// your actual decorator
Reflect.defineMetadata(FIELD_METADATA_KEY, field, target, propertyKey);
};
}
// list of keys
Reflect.getMetadata(FIELD_LIST_METADATA_KEY, Product.prototype)https://stackoverflow.com/questions/44627875
复制相似问题