gpt4 book ai didi

typescript - 获取 TypeScript 中的属性装饰器列表

转载 作者:搜寻专家 更新时间:2023-10-30 21:30:13 24 4
gpt4 key购买 nike

class Test {
@First()
@Second()
public someAttribute;
}

var t = new Test();
var decorators = t.getListOfAttributeDecorators("someAttribute");
console.log(decorators); // [First, Second]

我想实现“getListOfAttributeDecorators”函数,但不知道如何实现。或者有没有其他方法可以获取属性装饰器列表?

最佳答案

您可以使用 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

附言这是一个老问题,但是,我希望我的回答能对某人有所帮助。

关于typescript - 获取 TypeScript 中的属性装饰器列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41144335/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com