[英]How to get rid of `no-unused-expressions` eslint error, for `&&` and `?:` usage?
Problem statement:问题陈述:
this.componentC && this.componentC.render() // by default, this throws error , per
no-unused-expressions
eslint rulethis.componentC && this.componentC.render() // 默认情况下,根据
no-unused-expressions
eslint 规则,这会抛出错误
&&
is appropriate when you need to evaluate whether two expressions are truthy. &&
适用于需要评估两个表达式是否为真的情况。 If that isn't the situation - for example, if you need to test for expression1
's truthyness before evaluating some other expression (like a function call), then you should use if
statements.如果情况并非如此——例如,如果您需要在评估其他表达式(如函数调用)之前测试
expression1
的真实性,那么您应该使用if
语句。 To fix your original code:要修复您的原始代码:
if (this.componentC) this.componentC.render();
Linters warn about unused expressions because they're a code smell and are an indication that you're probably implementing something wrong, like here. Linters 会警告未使用的表达式,因为它们是代码异味,并且表明您可能执行了错误的操作,例如此处。
Similarly, with the conditional (ternary) operator, instead, if you have an unused expression:同样,使用条件(三元)运算符,如果您有一个未使用的表达式:
someCondition
? someFn1()
: someFn2();
if you're not using the result of the expression, you should use if/else
instead:如果您不使用表达式的结果,则应改用
if/else
:
if (someCondition) someFn1();
else someFn2();
One of the main goals of programming should be to write clear, understandable code - don't shirk on code character count just for the heck of it, unless you're golfing .编程的主要目标之一应该是编写清晰、易懂的代码——不要仅仅为了代码字符数而逃避,除非你在打高尔夫球。
Below is my recommendation:以下是我的建议:
Just add the below overrides
entry to your .eslintrc.json/js
只需将以下
overrides
条目添加到您的.eslintrc.json/js
overrides: [{
files: ["./src/*.js"],
rules: {
"no-unused-expressions": [{
"allowShortCircuit": true,
"allowTernary": true
}]
},
}
],
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.