Obtener lista de decoradores de atributos en TypeScript
class Test {
@First()
@Second()
public someAttribute;
}
var t = new Test();
var decorators = t.getListOfAttributeDecorators("someAttribute");
console.log(decorators); // [First, Second]
Me gustaría implementar la función "getListOfAttributeDecorators", pero no sé cómo. ¿O hay alguna otra manera de obtener la lista de decoradores de atributos?
Respuesta #1
Puedes obtener datos sobre tus decoradores personalizados usando reflect-metadata. Es posible definiendo metadatos de una propiedad dentro de la implementación del decorador - ver en codesandbox. Sin embargo, solo puedes hacerlo con tus decoradores personalizados; las bibliotecas de terceros a menudo también usan este enfoque con una clave de metadatos diferente.
// 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);
No olvides agregar "emitDecoratorMetadata": true a tu tsconfig.json para poder manipular con los metadatos.
Bono: implementación con soporte para decoradores de clases - ver en codesandox
P.D. Es la vieja pregunta, sin embargo, espero que mi respuesta ayude a alguien.
Respuesta #2
Necesitarás mantener una estructura de datos que contenga esa información, algo como:
const REGISTRY = new Map<string, Map<string, string[]>>();
function register(cls: string, property: string, decorator: string) {
let map: Map<string, string[]>;
if (REGISTRY.has(cls)) {
map = REGISTRY.get(cls);
} else {
map = new Map<string, string[]>();
REGISTRY.set(cls, map);
}
let list: string[];
if (map.has(property)) {
list = map.get(property);
} else {
list = [];
map.set(property, list);
}
if (list.indexOf(decorator) < 0) {
list.push(decorator);
}
}
function First() {
return function (cls: any, property: string) {
register(cls.constructor.name, property, "First");
}
}
function Second() {
return function (cls: any, property: string) {
register(cls.constructor.name, property, "Second");
}
}
class Test {
@First()
@Second()
public someAttribute;
public getListOfAttributeDecorators(property: string): string[] {
const name = this.constructor.name;
return !REGISTRY.has(name) ? [] : REGISTRY.get(name).get(property);
}
}
let t = new Test();
let names = t.getListOfAttributeDecorators("someAttribute");
console.log(names); // ["Second", "First"]
(código en el área de juegos)
