arrow-body-style
要求箭頭函式主體周圍使用大括號
箭頭函式的主體有兩種語法形式。它們可以使用區塊主體(用大括號表示)() => { ... }
或單一表達式 () => ...
定義,後者的值會隱含地回傳。
規則詳情
此規則可以強制或禁止在箭頭函式主體周圍使用大括號。
選項
此規則接受一個或兩個選項。第一個是字串,可以是
"always"
強制在函式主體周圍使用大括號"as-needed"
強制在可以省略大括號的地方不使用(預設)"never"
強制在函式主體周圍不使用大括號(將箭頭函式限制為回傳表達式的角色)
第二個選項是物件,用於在第一個選項為 "as-needed"
時進行更精細的設定。目前,唯一可用的選項是 requireReturnForObjectLiteral
,一個布林屬性。預設值為 false
。如果設定為 true
,則它要求物件字面值使用大括號和明確的回傳。
"arrow-body-style": ["error", "always"]
always
使用 "always"
選項時,不正確程式碼範例
在 Playground 中開啟
/*eslint arrow-body-style: ["error", "always"]*/
const foo = () => ;
使用 "always"
選項時,正確程式碼範例
在 Playground 中開啟
/*eslint arrow-body-style: ["error", "always"]*/
const foo = () => {
return 0;
};
const bar = (retv, name) => {
retv[name] = true;
return retv;
};
as-needed
使用預設 "as-needed"
選項時,不正確程式碼範例
在 Playground 中開啟
/*eslint arrow-body-style: ["error", "as-needed"]*/
const foo = () => ;
const bar = () => ;
使用預設 "as-needed"
選項時,正確程式碼範例
在 Playground 中開啟
/*eslint arrow-body-style: ["error", "as-needed"]*/
const foo1 = () => 0;
const foo2 = (retv, name) => {
retv[name] = true;
return retv;
};
const foo3 = () => ({
bar: {
foo: 1,
bar: 2,
}
});
const foo4 = () => { bar(); };
const foo5 = () => {};
const foo6 = () => { /* do nothing */ };
const foo7 = () => {
// do nothing.
};
const foo8 = () => ({ bar: 0 });
requireReturnForObjectLiteral
此選項僅在與
"as-needed"
選項結合使用時適用。
使用 { "requireReturnForObjectLiteral": true }
選項時,不正確程式碼範例
在 Playground 中開啟
/*eslint arrow-body-style: ["error", "as-needed", { "requireReturnForObjectLiteral": true }]*/
const foo = () => ();
const bar = () => ();
使用 { "requireReturnForObjectLiteral": true }
選項時,正確程式碼範例
在 Playground 中開啟
/*eslint arrow-body-style: ["error", "as-needed", { "requireReturnForObjectLiteral": true }]*/
const foo = () => {};
const bar = () => { return { bar: 0 }; };
never
使用 "never"
選項時,不正確程式碼範例
在 Playground 中開啟
/*eslint arrow-body-style: ["error", "never"]*/
const foo = () => ;
const bar = (retv, name) => ;
使用 "never"
選項時,正確程式碼範例
在 Playground 中開啟
/*eslint arrow-body-style: ["error", "never"]*/
const foo = () => 0;
const bar = () => ({ foo: 0 });
版本
此規則在 ESLint v1.8.0 中引入。