Skip to content

Commit 2a58447

Browse files
committed
fix(formatter): correct printing comments for the end of union type (#14498)
1 parent 4994872 commit 2a58447

File tree

3 files changed

+24
-3
lines changed

3 files changed

+24
-3
lines changed

crates/oxc_formatter/src/write/union_type.rs

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,7 @@ pub struct FormatTSType<'a, 'b> {
130130
}
131131

132132
impl<'a> Format<'a> for FormatTSType<'a, '_> {
133-
fn fmt(&self, f: &mut crate::formatter::Formatter<'_, 'a>) -> FormatResult<()> {
133+
fn fmt(&self, f: &mut Formatter<'_, 'a>) -> FormatResult<()> {
134134
let format_element = format_once(|f| {
135135
self.element.fmt(f)?;
136136
Ok(())
@@ -158,7 +158,7 @@ impl<'a> Format<'a> for FormatTSType<'a, '_> {
158158
// // comment
159159
// | B
160160
// ```
161-
// If there is a leading own line comment between `|` and the next node, we need to put print comments
161+
// If there is a leading own line comment between `|` and the next node, we need to put printing comments
162162
// before `|` instead of after it.
163163
if f.comments().has_leading_own_line_comment(next_node_span.start) {
164164
let comments = f.context().comments().comments_before(next_node_span.start);
@@ -171,7 +171,9 @@ impl<'a> Format<'a> for FormatTSType<'a, '_> {
171171
write!(f, [soft_line_break_or_space()])?;
172172
}
173173
write!(f, ["|"])
174-
} else {
174+
} else if let AstNodes::TSUnionType(parent) = self.element.parent
175+
&& parent.needs_parentheses(f)
176+
{
175177
// ```ts
176178
// type Foo = (
177179
// | "thing1" // comment1
@@ -183,6 +185,8 @@ impl<'a> Format<'a> for FormatTSType<'a, '_> {
183185
let comments =
184186
f.context().comments().end_of_line_comments_after(self.element.span().end);
185187
FormatTrailingComments::Comments(comments).fmt(f)
188+
} else {
189+
Ok(())
186190
}
187191
}
188192
}
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
interface _KeywordDef {
2+
type?: JSONType | JSONType[] // data types that keyword applies to
3+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
source: crates/oxc_formatter/tests/fixtures/mod.rs
3+
---
4+
==================== Input ====================
5+
interface _KeywordDef {
6+
type?: JSONType | JSONType[] // data types that keyword applies to
7+
}
8+
9+
==================== Output ====================
10+
interface _KeywordDef {
11+
type?: JSONType | JSONType[]; // data types that keyword applies to
12+
}
13+
14+
===================== End =====================

0 commit comments

Comments
 (0)