You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 17:45:03