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

如何避免IntelliJ/WebStorm格式化TypeScript构造函数时添加换行?

TypeScript构造函数格式化问题

在TypeScript开发中,我们常使用如下形式的构造函数:

export class SlotController {

  /*
   * This injects the dependency and assigns it to a field
   * It is NOT an unused variable
   */
  constructor(private service: SlotService) {}

  [...]
}

但使用IntelliJ/WebStorm进行自动格式化后,会在构造函数的闭合大括号前添加换行,变为:

constructor(private service: SlotService) {
}

尝试了Code Styles > TypeScript下的相关设置,但并未生效,请问该如何解决此问题?


解决方法

  • 打开IDE设置(快捷键:Windows/Linux为Ctrl+Alt+S,Mac为Cmd+,)
  • 依次进入Editor > Code Style > TypeScript > Wrapping and Braces
  • 在Braces placement分组中,找到Empty blocks选项,选择「Put on the same line」
  • 点击「Apply」「OK」保存设置

完成上述操作后,空构造函数的大括号会保持在同一行,不会被格式化拆分。

如果设置后仍未生效,需检查是否启用了ESLint等外部格式化工具:

  • 进入Settings > Languages & Frameworks > JavaScript > Code Quality Tools > ESLint
  • 若勾选了「Run eslint --fix on save」,需在项目的.eslintrc配置文件中添加规则:
"rules": {
  "brace-style": ["error", "1tbs", { "allowSingleLine": true }]
}

内容的提问来源于stack exchange,提问作者Arnaud Denoyelle

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 12:37:04