Fix comment in union type get duplicated (#18393)

This commit is contained in:
fisker Cheung authored and GitHub committed 2025-12-02 01:46:31 +08:00
1 parent cfa92c1b6d
commit 7efb988c67
4 files changed
+87 -1

No files matched your search

+13
View File
@@ -0,0 +1,13 @@
#### Fix comment inside union type get duplicated (#18393 by @fisker)
<!-- prettier-ignore -->
```tsx
// Input
type Foo = (/** comment */ a | b) | c;
// Prettier stable
type Foo = /** comment */ (/** comment */ a | b) | c;
// Prettier main
type Foo = /** comment */ (a | b) | c;
```
+6 -1
View File
@@ -19,6 +19,7 @@ import {
hasLeadingOwnLineComment, hasLeadingOwnLineComment,
isConditionalType, isConditionalType,
isTypeAlias, isTypeAlias,
isUnionType,
} from "../utilities/index.js"; } from "../utilities/index.js";
// `TSUnionType` and `UnionTypeAnnotation` // `TSUnionType` and `UnionTypeAnnotation`
@@ -77,7 +78,11 @@ function printUnionType(path, options, print) {
return printComments(path, printedType, options); return printComments(path, printedType, options);
}, "types"); }, "types");
const { leading, trailing } = printCommentsSeparately(path, options); const { leading, trailing } =
// If it's `types` of union type, parent will print comment for us
path.key === "types" && isUnionType(path.parent)
? { leading: "", trailing: "" }
: printCommentsSeparately(path, options);
if (shouldHug) { if (shouldHug) {
return [leading, join(" | ", printed), trailing]; return [leading, join(" | ", printed), trailing];
@@ -0,0 +1,19 @@
type A1 = | /**
* octahedralRhinocerosTransformer
*/
a
| (b | c);
type A2 = | /**
* hippopotamicKangarooMutator
*/
(a | b)
| c;
type A4 =
(
A | B // comment 1
) | (
// comment2
A | B
)
@@ -95,3 +95,52 @@ type A3 =
================================================================================ ================================================================================
`; `;
exports[`18389.ts format 1`] = `
====================================options=====================================
parsers: ["typescript", "flow"]
printWidth: 80
| printWidth
=====================================input======================================
type A1 = | /**
* octahedralRhinocerosTransformer
*/
a
| (b | c);
type A2 = | /**
* hippopotamicKangarooMutator
*/
(a | b)
| c;
type A4 =
(
A | B // comment 1
) | (
// comment2
A | B
)
=====================================output=====================================
type A1 =
| /**
* octahedralRhinocerosTransformer
*/
a
| (b | c);
type A2 =
| /**
* hippopotamicKangarooMutator
*/
(a | b)
| c;
type A4 =
| (A | B) // comment 1
// comment2
| (A | B);
================================================================================
`;