【问题标题】:TS. Enumerate the decoratorsTS。枚举装饰器
【发布时间】:2022-11-28 09:17:41
【问题描述】:

我有一个问题——我正在尝试编写自己的 Injectable 实现,我需要知道我的类中是否有特定的装饰器。我如何枚举类的所有装饰器?例如,我有以下代码。我只需要知道我是否在 MyClass 中将“myDecorator”作为装饰器

function myDecorator(ctor: Function):void{
    console.log(ctor)}

@myDecorator

class MyClass{
    static isInjectable: boolean;
    public a: number = 5;
    constructor() {
        this.a = 5;
    }
}

也许,我可以使用 Reflect-API 来解决这个问题,但我仍然不知道如何正确使用它

【问题讨论】:

    标签: typescript typescript-decorator


    【解决方案1】:

    你需要的是像这样定义一个装饰器:

    export function Injectable(constructor: Function): void{
        Reflect.defineMetadata("isInjectable", Injectable, constructor);
    }
    
    export class Injector<T>{
        get(ctor: {new() : T}): T{
            console.log(Reflect.getMetadata("isInjectable", ctor));
                return new ctor();
        }
    }
    

    然后尝试从注射器班级。

    【讨论】:

      猜你喜欢
      • 2018-05-17
      • 2010-11-12
      • 2021-03-01
      • 2012-07-28
      • 2021-04-18
      • 2021-12-29
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多