Typescript decorator-此处接受的参数太少,无法用作decorator

Typescript decorator-此处接受的参数太少,无法用作decorator,typescript,Typescript,我正在尝试编写一个decorator,该decorator接受一个方法,如果该方法没有在指定的超时(使用方法参数指定)内完成,则会抛出一个错误。如果不指定超时,则会导致方法运行时,就好像不存在参数一样 export const setMethodTimeout = (): Function => { return function(target: any, propertyKey: string | symbol, descriptor: PropertyDescriptor) {

我正在尝试编写一个decorator,该decorator接受一个方法,如果该方法没有在指定的超时(使用方法参数指定)内完成,则会抛出一个错误。如果不指定超时,则会导致方法运行时,就好像不存在参数一样

export const setMethodTimeout = (): Function => {
  return function(target: any, propertyKey: string | symbol, descriptor: PropertyDescriptor) {
    const context = this;
    const args: DecoratorArgumentType = arguments;
    if (args.timeout) {
      const timer = setTimeout(() => {
        throw new Error('The method did not finish before the specified timeout.');
      }, args.timeout);
      const originalMethod = descriptor.value;
      descriptor.value = function() {
        originalMethod
          .apply(context, args)
          .then((result: any) => {
            clearTimeout(timer);
            return result;
          })
          .catch((e: Error) => {
            throw e;
          });
      };
    }
    return descriptor;
  };
};
现在,当我尝试在我的类方法上使用此装饰器时:

@setMethodTimeout
public async getMap(params: GetMapParams, api: ApiType, reqConfig?: RequestConfiguration): Promise<Blob> {
   //...
}
@setMethodTimeout
公共异步getMap(参数:GetMapParams,api:ApiType,reqConfig?:RequestConfiguration):承诺{
//...
}
我得到以下类型脚本错误:

“setMethodTimeout”接受的参数太少,无法在此处用作装饰器。您是想先调用它并编写“@setMethodTimeout()”吗


为什么会发生这种情况?

这需要一个函数调用,因为您要用附加函数
setMethodTimeout
包装装饰程序。如果按如下方式删除函数调用语法,它将在没有函数调用语法的情况下工作:

export const function setMethodTimeout(target: any, propertyKey: string | symbol, descriptor: PropertyDescriptor) {
    const context = this;
    const args: DecoratorArgumentType = arguments;
    if (args.timeout) {
      const timer = setTimeout(() => {
        throw new Error('The method did not finish before the specified timeout.');
      }, args.timeout);
      const originalMethod = descriptor.value;
      descriptor.value = function() {
        originalMethod
          .apply(context, args)
          .then((result: any) => {
            clearTimeout(timer);
            return result;
          })
          .catch((e: Error) => {
            throw e;
          });
      };
    }
    return descriptor;
};

您是否尝试添加大括号
@setMethodTimeout()