首页 文章

用于setTimeout()函数的TypeScript装饰器

提问于
浏览
2

我已经开始学习如何在我的应用程序中实现TypeScript装饰器 . 所以我从 setTimeout 开始 . 它是一个方法装饰器,它在一段时间后执行方法 .

例如:

@Decorators.timeout()
 public someMethod () {}

这是我的实现:

export class Decorators {

  public static timeout (target: Object, propertyKey: string, descriptor: TypedPropertyDescriptor<any>): any {

    let originalMethod = descriptor.value;
    let decArguments = arguments;

    descriptor.value = function Timeout () {

        setTimeout(() => {

          originalMethod.apply(this, decArguments);

        }, 2000);
    };

    return descriptor;

  }

}

这是我得到的错误:

提供的参数与呼叫目标的任何签名都不匹配

可能是什么问题呢?

1 回答

  • 4

    你在 Timeout() 函数中缺少 args ,你应该将 args 传递给原始方法:

    descriptor.value = function Timeout (...args) {
    
        setTimeout(() => {
    
          originalMethod.apply(this, args);
    
        }, 2000);
    };
    

    然后你应该删除这一行,因为它没有做任何事情:

    let decArguments = arguments;
    

相关问题