如何避免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
相关产品推荐
相关产品推荐

