【问题标题】:typescript decorators with arrow functions带有箭头功能的打字稿装饰器
【发布时间】:2020-03-28 14:36:18
【问题描述】:

我必须在此实现中实现箭头函数,并且我需要将来自 AWS 的输入转换为自定义模型,以避免对每个 API 执行相同的逻辑。我想过使用装饰器来完成每个功能。由于编译器将其视为属性,因此它不会找到描述符属性并引发异常。有没有办法欺骗编译器将箭头函数识别为实际函数并传递描述符?

 @API(EndpointType.POST)
  public login = async (event: Input): Promise<APIGatewayProxyResult> => {
     ... logic
  }

   export function API(apiType:EndpointType): any {
      return (target: any, propertyKey: string, descriptor?: TypedPropertyDescriptor<any>) => {
         descriptor.value = function(request) {
             ... logic
             const bindedOriginalFunction = originalFunction.bind(this)
             const result = bindedOriginalFunction(finalResult);
             return result
         }
       return descriptor;
   }

【问题讨论】:

    标签: typescript javascript-decorators


    【解决方案1】:

    必须是箭头函数吗?

    class Foo {
      async login(event: Input): Promise<APIGatewayProxyResult> { ... }
    }
    

    在您的情况下,箭头函数不是方法(对象拥有的函数)。您有一个属性,其中包含其他人拥有的函数(箭头函数)。

    【讨论】:

    • 不幸的是,我遵循 AWS 控制器服务存储库模式,如果我使用普通函数,它不会将服务注入到类中,它需要依赖注入,这是我将以后想解决
    猜你喜欢
    • 2015-12-12
    • 2018-09-30
    • 1970-01-01
    • 2018-05-10
    • 1970-01-01
    • 2017-10-10
    • 2020-04-25
    • 2018-11-07
    • 2019-09-30
    相关资源
    最近更新 更多