【问题标题】:Parameter decorators with Babel (like in Typescript)带有 Babel 的参数装饰器(如在 Typescript 中)
【发布时间】:2018-03-16 19:37:54
【问题描述】:

有没有办法在 Typescript 中使用带有 Babel 的参数装饰器。

打字稿代码示例:

class A {
   constructor(@Inject('IService') private service: IService) {

   }
}

我想用Babel写这段代码:

class A {
   constructor(@Inject('IService') service) {
      this.service = service;
   }
}

我还没有找到关于这个问题的任何信息。在某个预设中是否有类似的插件可以做到这一点?

如果没有拐杖就无法做到这一点,有没有办法在构造函数上使用装饰器?示例

class A {
   @Inject('IService')
   constructor(service) {
      this.service = service;
   }
}

谢谢。

【问题讨论】:

  • 这是装饰器转换:babeljs.io/docs/plugins/transform-decorators。但是你真的需要吗?取决于它应该如何工作,为什么不在构造函数中写this.service = getIService()
  • 我同意。为此使用装饰器似乎会使它变得更加复杂。
  • 我发布这个问题是为了了解它是否可能,而不是对它的外观进行评论。谢谢。
  • 我希望他们能够在 ES7 中完成这项工作,它对于注入和其他实用程序非常方便。关于最后一个问题,我猜你可以这样做jsfiddle.net/mm52n6se

标签: parameters babeljs decorator ecmascript-next


【解决方案1】:

Babel does not currently support this feature

您现在有两个选择:

  • 改用 babel-plugin-parameter-decorator
  • 使用 tsc

很遗憾,第一个选项在细节上并不完美,如下例所示:

@Get('/:id')
getUser(@Param("id") id: number) {
  cosnole.log(typeof id); // string
}

【讨论】:

    猜你喜欢
    • 2016-02-11
    • 2018-07-21
    • 2014-07-21
    • 2022-08-15
    • 2023-03-09
    • 2018-01-07
    • 2022-12-28
    • 2018-06-08
    相关资源
    最近更新 更多