VS Code保存后所需括号消失,React+TypeScript下如何解决?
解决Prettier自动移除计算式括号的问题(React+TypeScript)
问题描述
我正在编写一个计算基础代谢率(Basal Metabolic Rate,BMR)的函数,需要为部分计算内容添加括号来匹配公式的可读性要求,但每次在VS Code中保存文件后,这些括号都会被Prettier自动移除。团队不允许修改Prettier配置,请问该如何解决?
技术栈:React + TypeScript
计算公式:
- 男性:BMR = 88.362 + (13.397 × 体重kg) + (4.799 × 身高cm) – (5.677 × 年龄)
- 女性:BMR = 447.593 + (9.247 × 体重kg) + (3.098 × 身高cm) – (4.330 × 年龄)
当前代码:
function handleSubmit(event: any) { event.preventDefault(); if (male) { const newGeb = 88.362 + 13.397 * Number(peso) + 4.799 * Number(altura) - 5.677 * Number(edad); setGeb(newGeb); } else if (female) { const newGeb = 447.593 + 9.247 * Number(peso) + 3.098 * Number(altura) - 4.33 * Number(edad); setGeb(newGeb); } setIsGebModalOpen(true); event.target.reset(); }
可行解决方法
Prettier会自动移除不影响运算优先级的冗余括号,要保留括号的话,可通过以下两种方式实现:
1. 拆分计算步骤,用中间变量替代(推荐)
把公式中每个带括号的分组单独赋值给变量,既匹配公式的结构逻辑,又能避免Prettier移除括号,同时还提升了代码可读性:
function handleSubmit(event: any) { event.preventDefault(); if (male) { const weightFactor = 13.397 * Number(peso); const heightFactor = 4.799 * Number(altura); const ageFactor = 5.677 * Number(edad); const newGeb = 88.362 + weightFactor + heightFactor - ageFactor; setGeb(newGeb); } else if (female) { const weightFactor = 9.247 * Number(peso); const heightFactor = 3.098 * Number(altura); const ageFactor = 4.33 * Number(edad); const newGeb = 447.593 + weightFactor + heightFactor - ageFactor; setGeb(newGeb); } setIsGebModalOpen(true); event.target.reset(); }
2. 添加无意义的嵌套括号(应急使用)
如果不想拆分变量,可以给目标表达式套一层额外的括号,让Prettier认为这是有意的分组操作,从而保留外层括号:
function handleSubmit(event: any) { event.preventDefault(); if (male) { const newGeb = 88.362 + ((13.397 * Number(peso))) + ((4.799 * Number(altura))) - ((5.677 * Number(edad))); setGeb(newGeb); } else if (female) { const newGeb = 447.593 + ((9.247 * Number(peso))) + ((3.098 * Number(altura))) - ((4.33 * Number(edad))); setGeb(newGeb); } setIsGebModalOpen(true); event.target.reset(); }
注意:这种写法会让代码略显臃肿,仅推荐临时应急场景使用。
内容的提问来源于stack exchange,提问作者Michael Horvilleur
相关产品推荐
相关产品推荐

