【问题标题】:tslint one line rule misplaced 'else'tslint 单行规则错位'else'
【发布时间】:2016-05-17 14:55:46
【问题描述】:

我在tslint.json 中有这样的config one line rule

one-line": [true,
      "check-open-brace",
      "check-catch",
      "check-else",
      "check-whitespace"
    ],

当我有这样的代码行时:

if(SomethingTrue) { next("a"); }
else { next("b"); }

我收到警告:

(one-line) file.ts[17, 9]: misplaced 'else'

为什么会这样? 拥有一个line else 是不好的做法吗?

【问题讨论】:

    标签: typescript tslint


    【解决方案1】:
    if (condition is true) {
      // do something;
    }
    else {
      // do something else;
    }
    

    请注意else 位于} 旁边

    if (condition is true) {
      // do something;
    } else {
      // do something else;
    }
    

    【讨论】:

      【解决方案2】:

      你有:

      else { next("b"); }
      

      否则必须是一个一行。所以:

      else { 
          next("b"); 
      }
      

      另外一行是不好的做法吗?

      只是更容易阅读。它是一致性的风格指南。

      【讨论】:

      • 是的,我刚刚意识到 "check-else" 规则负责检查。
      • 那么它将是 1 line ifmultiple line else 我认为这有点连线
      • 也添加check-if
      【解决方案3】:

      根据tslint docs,问题是当"check-else"one-line 下指定时,else 必须与 if 的右大括号位于同一行。

      所以在你的情况下,而不是:

      if(SomethingTrue) { next("a"); }
      else { next("b"); }
      

      使用这种格式:

      if(SomethingTrue) { next("a"); } else { next("b"); }
      

      【讨论】:

      • 感谢您提示负责的规则 :)
      【解决方案4】:
      if (condition) {
        // Your Code
      } else {
        // Your Code
      }
      

      If 的结尾和else 的开头应该在同一行。

      【讨论】:

        猜你喜欢
        • 2019-05-12
        • 1970-01-01
        • 2020-07-24
        • 2017-08-08
        • 2016-02-04
        • 2020-03-01
        • 2019-03-26
        • 2020-02-26
        • 2020-05-25
        相关资源
        最近更新 更多