Skip to content
← Back to rules

eslint/arrow-body-style 样式

🛠️ An auto-fix is available for this rule.

作用 ​

此规则可以强制或禁止在箭头函数体周围使用花括号。 箭头函数可以使用以下任一形式:

  • 块体 () => { ... }
  • 或简洁体 () => expression,带有隐式返回。

为什么不好? ​

不一致地使用块体与简洁体会使代码更难阅读。 简洁体仅限于单个表达式,其值会被隐式返回。

示例 ​

"never" ​

使用 never 选项时,此规则的错误代码示例:

js
/* arrow-body-style: ["error", "never"] */

/* ✘ 不好: */
const foo = () => {
  return 0;
};

使用 never 选项时,此规则的正确代码示例:

js
/* arrow-body-style: ["error", "never"] */

/* ✔ 好: */
const foo = () => 0;
const bar = () => ({ foo: 0 });

"always" ​

使用 always 选项时,此规则的错误代码示例:

js
/* arrow-body-style: ["error", "always"] */

/* ✘ 不好: */
const foo = () => 0;

使用 always 选项时,此规则的正确代码示例:

js
/* arrow-body-style: ["error", "always"] */

/* ✔ 好: */
const foo = () => {
  return 0;
};

"as-needed"(默认) ​

使用 as-needed 选项时,此规则的错误代码示例:

js
/* arrow-body-style: ["error", "as-needed"] */

/* ✘ 不好: */
const foo = () => {
  return 0;
};

使用 as-needed 选项时,此规则的正确代码示例:

js
/* arrow-body-style: ["error", "as-needed"] */

/* ✔ 好: */
const foo1 = () => 0;

const foo2 = (retv, name) => {
  retv[name] = true;
  return retv;
};

const foo3 = () => {
  bar();
};

"as-needed" 配合 requireReturnForObjectLiteral ​

使用 { "requireReturnForObjectLiteral": true } 选项时,此规则的错误代码示例:

js
/* arrow-body-style: ["error", "as-needed", { "requireReturnForObjectLiteral": true }] */

/* ✘ 不好: */
const foo = () => ({});
const bar = () => ({ bar: 0 });

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

js
/* arrow-body-style: ["error", "as-needed", { "requireReturnForObjectLiteral": true }] */

/* ✔ 好: */
const foo = () => {};
const bar = () => {
  return { bar: 0 };
};

配置 ​

第一个选项 ​

类型:"as-needed" | "always" | "never"

"as-needed" ​

强制在可以省略大括号的地方不使用大括号(默认)。

"always" ​

强制在函数体周围使用大括号。

"never" ​

强制不在函数体周围使用大括号(将箭头函数限制为返回一个表达式的角色)。

第二个选项 ​

此选项是一个对象,包含以下属性:

requireReturnForObjectLiteral ​

类型:boolean

默认:false

要求对象字面量使用大括号并显式 return。此选项仅在第一个选项为 "as-needed" 时适用。

如何使用 ​

To enable this rule using the config file or in the CLI, you can use:

json
{
  "rules": {
    "arrow-body-style": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  rules: {
    "arrow-body-style": "error",
  },
});
bash
oxlint --deny arrow-body-style

版本 ​

此规则于 v1.4.0 中添加。

参考 ​