【问题标题】:Is there a way to ignore "Missing return type on function" for Angular lifecycle methods?有没有办法忽略 Angular 生命周期方法的“函数缺少返回类型”?
【发布时间】:2021-09-08 22:13:45
【问题描述】:

我们正在使用 Angular,我正在尝试从 tslint 切换到 eslint。 引发大约 600 个警告的规则是 Missing return type on function 来自eslint@typescript-eslint/explicit-module-boundary-types

我明白我应该为我的函数使用返回类型以及如何做到这一点。不过,Angular 中的生命周期方法几乎没有用处。我应该从ngOnInit返回什么?

所以问题是:我怎样才能对每个函数都使用这个规则,而不是 ngOnInitngOnDestroy 等?

ngOnInit(): void { // meh
    ...
}

ngOnInit() { // yay
    ...
}

以防万一,我的 .eslintrc.json:

extends": [
    "plugin:@angular-eslint/recommended",
    "plugin:@angular-eslint/template/process-inline-templates",
    "plugin:@typescript-eslint/recommended",
    "plugin:prettier/recommended"
],

【问题讨论】:

  • 你的“meh”和“yay”例子有什么区别?您的意思是从其中一个中省略类型声明吗?

标签: angular typescript eslint


【解决方案1】:

我没有对其进行测试,但看起来该规则接受 allowedNames 选项,您可以在其中传递一组不被检查的方法名称。

请注意,这也会禁用对方法参数的类型检查。

https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/explicit-module-boundary-types.md

【讨论】:

    【解决方案2】:

    根据@Ibsn 的回答,我可以想出这个配置:

    "rules": {
        "@typescript-eslint/explicit-module-boundary-types": [
          "warn",
          {
            "allowedNames": ["ngOnInit", "ngOnDestroy", "ngAfterViewInit", "ngOnChanges"]
          }
        ]
    }
    

    【讨论】:

      【解决方案3】:

      有办法解决这个问题:

      1. 在每行之前添加错误注释,如下所示,以忽略每个错误:
       // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
      
      
      1. 只需全局忽略此类错误:
          
          "extends": [
              "plugin:@angular-eslint/recommended",
              "plugin:@angular-eslint/template/process-inline-templates",
              "plugin:@typescript-eslint/recommended",
              "plugin:prettier/recommended"
          ],
          "plugins": ["unused-imports"],
          "rules": {
              "@typescript-eslint/explicit-module-boundary-types": "off"
          }
      

      【讨论】:

      • 再读一遍这个问题:“我怎样才能对每个函数使用这个规则,而不是 x & y”。 :)
      猜你喜欢
      • 2013-03-31
      • 2019-12-27
      • 1970-01-01
      • 2010-11-22
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 2013-07-02
      • 2014-08-17
      相关资源
      最近更新 更多