Skip to content

Commit e743d07

Browse files
a-tarasyuksandersn
andauthored
fix(55404): Remove braces from arrow function" generates invalid code in JavaScript (#55429)
Co-authored-by: Nathan Shively-Sanders <[email protected]>
1 parent 982f8be commit e743d07

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

src/services/refactors/addOrRemoveBracesToArrowFunction.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,13 @@ import {
1212
factory,
1313
first,
1414
getContainingFunction,
15+
getLeftmostExpression,
1516
getLocaleSpecificMessage,
1617
getTokenAtPosition,
1718
isArrowFunction,
1819
isBlock,
1920
isExpression,
21+
isObjectLiteralExpression,
2022
isReturnStatement,
2123
needsParentheses,
2224
rangeContainsRange,
@@ -147,7 +149,8 @@ function getConvertibleArrowFunctionAtPosition(file: SourceFile, startPosition:
147149
else if (refactorKindBeginsWith(removeBracesAction.kind, kind) && isBlock(func.body) && func.body.statements.length === 1) {
148150
const firstStatement = first(func.body.statements);
149151
if (isReturnStatement(firstStatement)) {
150-
return { func, addBraces: false, expression: firstStatement.expression, returnStatement: firstStatement };
152+
const expression = firstStatement.expression && isObjectLiteralExpression(getLeftmostExpression(firstStatement.expression, /*stopAtCallExpressions*/ false)) ? factory.createParenthesizedExpression(firstStatement.expression) : firstStatement.expression;
153+
return { func, addBraces: false, expression, returnStatement: firstStatement };
151154
}
152155
}
153156
return undefined;
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
/// <reference path='fourslash.ts' />
2+
3+
////const f = /*a*/(param) => {
4+
//// return {
5+
//// "a": 1,
6+
//// "b": 2,
7+
//// }[param];
8+
////}/*b*/;
9+
10+
goTo.select("a", "b");
11+
edit.applyRefactor({
12+
refactorName: "Add or remove braces in an arrow function",
13+
actionName: "Remove braces from arrow function",
14+
actionDescription: "Remove braces from arrow function",
15+
newContent:
16+
`const f = (param) => ({
17+
"a": 1,
18+
"b": 2,
19+
}[param]);`,
20+
});

0 commit comments

Comments
 (0)