Index

no-confusing-arrow

禁止使用可能与比较混淆的箭头函数

🔧 Fixable

此规则报告的一些问题可通过 --fix 命令行 选项自动修复

Important

This rule was deprecated in ESLint v8.53.0. It will be removed in v11.0.0. Please use the corresponding rule in @stylistic/eslint-plugin.

Learn more

箭头函数(=>)在语法上类似于某些比较运算符(><<=>=)。此规则警告不要在可能被误认为是比较运算符的地方使用箭头函数语法。

🌐 Arrow functions (=>) are similar in syntax to some comparison operators (>, <, <=, and >=). This rule warns against using the arrow function syntax in places where it could be confused with a comparison operator.

这是一个 => 的使用可能令人困惑的例子:

🌐 Here’s an example where the usage of => could be confusing:

// The intent is not clear
var x = a => 1 ? 2 : 3;
// Did the author mean this
var x = function (a) {
    return 1 ? 2 : 3;
};
// Or this
var x = a <= 1 ? 2 : 3;

规则详情

🌐 Rule Details

此规则的错误代码示例:

🌐 Examples of incorrect code for this rule:

在线运行
/*eslint no-confusing-arrow: "error"*/

var x = a => 1 ? 2 : 3;
var x = (a) => 1 ? 2 : 3;

符合此规则的正确代码示例:

🌐 Examples of correct code for this rule:

在线运行
/*eslint no-confusing-arrow: "error"*/

var x = a => (1 ? 2 : 3);
var x = (a) => (1 ? 2 : 3);
var x = (a) => {
    return 1 ? 2 : 3;
};
var x = a => { return 1 ? 2 : 3; };

选项

🌐 Options

此规则接受两个具有以下默认值的选项参数:

🌐 This rule accepts two options argument with the following defaults:

{
    "rules": {
        "no-confusing-arrow": [
            "error",
            { "allowParens": true, "onlyOneSimpleParam": false }
        ]
    }
}

allowParens 是一个布尔设置,可以是 true(默认)或 false

  1. true 放宽了规则,并接受括号作为有效的“防混淆”语法。
  2. false 即使表达式被括号封装也会发出警告

使用 {"allowParens": false} 选项时违反此规则的错误代码示例:

🌐 Examples of incorrect code for this rule with the {"allowParens": false} option:

在线运行
/*eslint no-confusing-arrow: ["error", {"allowParens": false}]*/

var x = a => (1 ? 2 : 3);
var x = (a) => (1 ? 2 : 3);

onlyOneSimpleParam 是一个布尔设置,可以是 truefalse(默认):

  1. true 放宽了规则,如果箭头函数的参数为 0 个或多于 1 个,或者参数不是标识符时,不会报错。
  2. false 无论参数如何都会发出警告。

使用 {"onlyOneSimpleParam": true} 选项时,此规则的正确代码示例:

🌐 Examples of correct code for this rule with the {"onlyOneSimpleParam": true} option:

在线运行
/*eslint no-confusing-arrow: ["error", {"onlyOneSimpleParam": true}]*/

() => 1 ? 2 : 3;
(a, b) => 1 ? 2 : 3;
(a = b) => 1 ? 2 : 3;
({ a }) => 1 ? 2 : 3;
([a]) => 1 ? 2 : 3;
(...a) => 1 ? 2 : 3;

版本

此规则是在 ESLint v2.0.0-alpha-2 中引入。

资源