如何配置ESLint实现箭头函数仅在实际有返回值时允许省略花括号
你需要的校验规则可以通过ESLint现有规则组合实现,无需引入第三方自定义规则。
配置方案
根据你的技术栈选择对应配置写入ESLint配置文件的rules字段即可:
JavaScript 项目
{ "arrow-body-style": ["error", "as-needed", { "disallowReturnless": true }], "no-unused-expressions": ["error", { "allowTernary": true, "allowShortCircuit": true, "allowTaggedTemplates": true }] }
TypeScript 项目
使用@typescript-eslint体系的规则校验精度更高,不会出现类型相关的误判:
{ "@typescript-eslint/arrow-body-style": ["error", "as-needed", { "disallowReturnless": true }], "@typescript-eslint/no-unused-expressions": ["error", { "allowTernary": true, "allowShortCircuit": true, "allowTaggedTemplates": true }], // 可选配置:允许箭头函数简写中使用void表达式 "@typescript-eslint/no-confusing-void-expression": ["error", { "ignoreArrowShorthand": true }] }
规则效果说明
上述配置完全匹配你给出的校验要求:
- 合法场景全部放行:隐式返回值的箭头函数、带花括号的箭头函数、使用
void显式标记无返回值的单表达式箭头函数均不会触发报错 - 非法场景拦截:没有返回值也没有加
void标记的单表达式箭头函数会触发错误,要求要么添加花括号包裹,要么显式补充void标记
内容的提问来源于stack exchange,提问作者Jared
相关产品推荐
相关产品推荐

