检查 属性 是否装饰有特定的注释 - 打字稿

Check if property is decorated with specific annotation - Typescript

如何确定特定的 属性 是否装饰有特定的注释?

例如这个 class:

class A {
    @DecoratedWithThis
    thisProp: number;
}

我怎么知道thisProp是用DecoratedWithThis装饰的?

我的用例:我使用另一个文件中的 class 生成代码,并使用 HTML 生成属性。

您能想到另一种解决方案吗?

据我所知,打字稿中没有原生方法,但有一种方法可以使用 'reflect-metadata' 库 https://github.com/rbuckton/reflect-metadata 来实现,这是对原生反射 api 的提议扩展.

装饰器只是在定义 class 时执行的函数。在你的情况下你想创建一个 属性 装饰器

function (target, propertyKey) {}

其中 target 是您的 Object.prototype,name 是 属性 name

根据 反映元数据文档

// define metadata on an object or property
Reflect.defineMetadata(metadataKey, metadataValue, target, propertyKey);

// get metadata value of a metadata key on the prototype chain of an object or property
let result = Reflect.getMetadata(metadataKey, target, propertyKey);

您可以通过向您的 属性 添加元数据来解决您的问题,您可以稍后阅读以检查 属性 是否已被修饰。

示例实现

import 'reflect-metadata';

const metadataKey = 'MyDecorator';

function MyDecorator(target, propertyKey) {
    Reflect.defineMetadata(metadataKey, true, target, propertyKey);
}

function myDecoratorUsingClass<T>(type:  Type<T>, propertyKey: string) {
    return myDecoratorUsingInstance(new type(), propertyKey);
}

function myDecoratorUsingInstance<T>(instance: T, propertyKey: string) {
  return !!Reflect.getMetadata(metadataKey, instance, propertyKey);
}

class MyClass {
   @MyDecorator
   property1;
   property2;
}

console.log(myDecoratorUsingClass(MyClass, 'property1')); // true
console.log(myDecoratorUsingClass(MyClass, 'property2')); // false

const instance = new MyClass();
console.log(myDecoratorUsingInstance(instance, 'property1')); // true
console.log(myDecoratorUsingInstance(instance, 'property2')); // false

注意 要使用 myDecoratorUsingClass 你的 class 应该有一个构造函数,其中所有参数都是可选的(或没有参数)

由于我不能作为新用户发表评论,所以我将其作为新答案发布,尽管它只是@h0ss 答案的升级版。

您可以使用 Reflect.hasMetadata(metadataKey, target, propertyKey)Reflect.hasOwnMetadata(metadataKey, target, propertyKey) 而不是 !!Reflect.getMetadata(metadataKey, instance, propertyKey),如此处所述 https://www.npmjs.com/package/reflect-metadata#api