Skip to content

Commit 983a613

Browse files
committed
fix(comments): preserve return type annotation comments
Signed-off-by: Kristinita <Kristinita@users.noreply.github.com>
1 parent 05446bd commit 983a613

1 file changed

Lines changed: 29 additions & 1 deletion

File tree

src/writer.ts

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,35 @@ export class Writer {
6969
const BODY = fn.body;
7070
const RETURN_TYPE = fn.returnType ? fn.returnType : '';
7171
const PARAMS = fn.params.join(', ');
72-
const arrowFunction = `${ASYNC}${GENERIC}(${PARAMS})${RETURN_TYPE} => ${BODY}`;
72+
73+
// Preserve a comment after a return type annotation
74+
const commentInside = this.sourceCode.getCommentsInside(node);
75+
let middleComment = '';
76+
77+
if (commentInside.length > 0) {
78+
// Find a comment between a return type and a function body
79+
const returnTypeComment = commentInside.find((candidateComment) => {
80+
// Get the start position of a candidate comment
81+
const commentStart = candidateComment.range[0];
82+
83+
/* If a return type exists, use its end position.
84+
Otherwise, use the end of the last function parameter */
85+
const returnTypeEnd = node.returnType ? node.returnType.range[1] : node.params[node.params.length - 1].range[1];
86+
87+
// Get the start position of a function body
88+
const bodyStart = node.body.range[0];
89+
90+
// Keep a comment between a return type and a function body
91+
return commentStart > returnTypeEnd && commentStart < bodyStart;
92+
});
93+
94+
// If a return type comment exists, get its text
95+
if (returnTypeComment) {
96+
middleComment = this.sourceCode.getText(returnTypeComment);
97+
}
98+
}
99+
100+
const arrowFunction = `${ASYNC}${GENERIC}(${PARAMS})${RETURN_TYPE}${middleComment} => ${BODY}`;
73101

74102
// Check if parentheses are needed due to operator precedence
75103
if (this.needsParentheses(node)) {

0 commit comments

Comments
 (0)