【问题标题】:Using typescript decorators to mandate a parameter in methods使用打字稿装饰器来强制方法中的参数
【发布时间】:2021-10-25 08:20:07
【问题描述】:

在一个打字稿项目中,当用户触发一个操作以及该操作完成时,大约有 2000 多个事件(方法)会被触发。因此,对于操作完成时触发的所有事件,我想要某种性能指标,因此参数“executionTime”应该是强制性的。 我计划在所有必须将执行时间作为参数存在的事件之上添加方法装饰器。下面是我的代码

class AllEvents {

    @performanceDecorator()
    public static firstEvent(param1: string, param2: string, executionTime: number): void {
        //some tasks...
    }

    @performanceDecorator()
    public static secondEvent(param1: string, param2: string): void {
        //some tasks...
    }

    @performanceDecorator()
    public static thirdEvent(param1: string, param2: string, executionTime: number): void {
        //some tasks...
    }
}

function performanceDecorator(value: boolean) {
    //..................
}

我是 typescript 的新手,无法弄清楚我应该在 function performanceDecorator 的主体中编写的代码,这样如果某些方法没有名为“executionTime”的参数,它会抛出错误。

【问题讨论】:

  • 由于 public static secondEvent 没有名为 'executionTime' 的参数,它应该会抛出错误。
  • 您是否希望每个事件都有第三个参数,即执行时间? '因为命名参数在 javascript 中不起作用,它解释了传递给函数的参数的顺序。或者接受一个对象作为所有函数的参数,并期望其中有一个名为 executionTime 的属性
  • @AkhilArjun 不是每个事件都会有第三个参数,只有选择性的。 '接受一个对象作为所有函数的参数,并期望一个名为 executionTime 的属性' 你能用一些代码 sn-p 解释上面的部分吗?

标签: javascript typescript decorator javascript-decorators


【解决方案1】:

扩展我之前的评论

由于在您的场景中无法固定参数的数量,因此没有简单的方法可以确定您的参数中的哪一个是执行时间。

所以创建一个带有预期参数的选项类作为它的属性。像这样

class EventOptions {
    public params: string[];
    public executionTime?: number;
}

class AllEvents {

    @performanceDecorator
    public static firstEvent(eventOptions: EventOptions): void {
        //some tasks...
        console.log(eventOptions.params, eventOptions.executionTime);
    }

    @performanceDecorator
    public static secondEvent(eventOptions: EventOptions): void {
        //some tasks...
    }

    @performanceDecorator
    public static thirdEvent(eventOptions: EventOptions): void {
        //some tasks...
    }
}

在这里,我将executionTime 作为可选参数来满足您的用例。但是您可以继续将其设为必填字段,然后您将不需要装饰器来检查该字段的有效性。 Typescript 会为您完成。


然后转到装饰器:

函数装饰器有三个参数,

  • target 是调用类,在本例中为 AllEvents
  • propertyKey 是字符串形式的方法名称
  • descriptor 是一个属性描述符。它包含与您的功能相关的所有元数据

我们可以把你的装饰器写成:

function performanceDecorator(
    target: Object,
    propertyKey: string,
    descriptor: PropertyDescriptor) {
        const originalMethod = descriptor.value;

        descriptor.value = (...args) => {
            if (!args[0].executionTime) {
                throw Error("Execution Time is missing!");
            }
            return originalMethod.apply(this, args);
        }
        return descriptor;
}

这里,我们先把原来的方法实现拿出来。然后使用条件来检查 executionTime 参数的可用性。如果不存在,我们会抛出一个错误。如果存在,我们称之为原始方法实现。

【讨论】:

    猜你喜欢
    • 2023-03-23
    • 1970-01-01
    • 2018-06-21
    • 2020-01-02
    • 1970-01-01
    • 2017-04-02
    • 2020-12-24
    • 1970-01-01
    • 2020-06-12
    相关资源
    最近更新 更多