【问题标题】:Get signature of method from method decorator从方法装饰器获取方法的签名
【发布时间】:2017-09-25 21:41:56
【问题描述】:

我有一个这样的方法装饰器:

export function NumberMethodDecorator(message: string) {
  return (target: object, propertyKey: string, descriptor?: TypedPropertyDescriptor<any>) => {
    // do some stuff here
  }
}

我想这样应用它:

class SomeClass {

  @NumberMethodDecorator("do some cool stuff")
  public someMethod(value: number) {

  }

}

但是,我想确保 NumberMethodDecorator 仅应用于签名为 (value: number) =&gt; any 的方法。

我该怎么做?

【问题讨论】:

    标签: typescript typescript2.0 typescript-decorator


    【解决方案1】:

    TypedPropertyDescriptor的类型参数中指定:

    export function NumberMethodDecorator(message: string) {
      return (
        target: object, propertyKey: string,
        descriptor?: TypedPropertyDescriptor<(value: number) => any>
      ) => {
        // do some stuff here
      };
    }
    

    那么当使用时:

    class SomeClass {
      @NumberMethodDecorator("") // ok
      someMethod(value: number) {
    
      }
    
      @NumberMethodDecorator("") // compile error
      otherMethod() {
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-07-01
      • 2020-01-02
      • 1970-01-01
      • 2011-03-15
      • 2023-02-16
      • 2020-01-11
      • 2012-03-06
      • 1970-01-01
      • 2019-01-01
      相关资源
      最近更新 更多