diff --git a/changelog_unreleased/javascript/pr-8557.md b/changelog_unreleased/javascript/pr-8557.md new file mode 100644 index 000000000..c6c9dcbb4 --- /dev/null +++ b/changelog_unreleased/javascript/pr-8557.md @@ -0,0 +1,22 @@ +#### Prefer leading comment when there is a comment on after "?" in conditional types ([#8557](https://github.com/prettier/prettier/pull/8557) by [@sosukesuzuki](https://github.com/sosukesuzuki)) + + +```ts +// Input +type A = B extends T + ? // comment + foo + : bar; + +// Prettier stable +type A = B extends T // comment + ? foo + : bar; + +// Prettier master +type A = B extends T + ? // comment + foo + : bar; + +``` diff --git a/src/language-js/comments.js b/src/language-js/comments.js index 1968ad646..99224c58c 100644 --- a/src/language-js/comments.js +++ b/src/language-js/comments.js @@ -407,7 +407,8 @@ function handleConditionalExpressionComments( if ( (!precedingNode || !isSameLineAsPrecedingNode) && enclosingNode && - enclosingNode.type === "ConditionalExpression" && + (enclosingNode.type === "ConditionalExpression" || + enclosingNode.type === "TSConditionalType") && followingNode ) { addLeadingComment(followingNode, comment); diff --git a/tests/typescript/conditional-types/__snapshots__/jsfmt.spec.js.snap b/tests/typescript/conditional-types/__snapshots__/jsfmt.spec.js.snap index 73ab426ab..6326bf563 100644 --- a/tests/typescript/conditional-types/__snapshots__/jsfmt.spec.js.snap +++ b/tests/typescript/conditional-types/__snapshots__/jsfmt.spec.js.snap @@ -1,5 +1,25 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP +exports[`comments.ts format 1`] = ` +====================================options===================================== +parsers: ["typescript"] +printWidth: 80 + | printWidth +=====================================input====================================== +type A = B extends T + ? // comment + foo + : bar; + +=====================================output===================================== +type A = B extends T + ? // comment + foo + : bar; + +================================================================================ +`; + exports[`conditonal-types.ts format 1`] = ` ====================================options===================================== parsers: ["typescript"] diff --git a/tests/typescript/conditional-types/comments.ts b/tests/typescript/conditional-types/comments.ts new file mode 100644 index 000000000..b6920fec3 --- /dev/null +++ b/tests/typescript/conditional-types/comments.ts @@ -0,0 +1,4 @@ +type A = B extends T + ? // comment + foo + : bar;