fix(55404): Remove braces from arrow function" generates invalid code in JavaScript (#55429)

Co-authored-by: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com>
This commit is contained in:
Oleksandr T 2023-09-23 02:14:06 +03:00 committed by GitHub
parent 982f8be6f2
commit e743d070ea
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 24 additions and 1 deletions

View File

@ -12,11 +12,13 @@ import {
factory,
first,
getContainingFunction,
getLeftmostExpression,
getLocaleSpecificMessage,
getTokenAtPosition,
isArrowFunction,
isBlock,
isExpression,
isObjectLiteralExpression,
isReturnStatement,
needsParentheses,
rangeContainsRange,
@ -147,7 +149,8 @@ function getConvertibleArrowFunctionAtPosition(file: SourceFile, startPosition:
else if (refactorKindBeginsWith(removeBracesAction.kind, kind) && isBlock(func.body) && func.body.statements.length === 1) {
const firstStatement = first(func.body.statements);
if (isReturnStatement(firstStatement)) {
return { func, addBraces: false, expression: firstStatement.expression, returnStatement: firstStatement };
const expression = firstStatement.expression && isObjectLiteralExpression(getLeftmostExpression(firstStatement.expression, /*stopAtCallExpressions*/ false)) ? factory.createParenthesizedExpression(firstStatement.expression) : firstStatement.expression;
return { func, addBraces: false, expression, returnStatement: firstStatement };
}
}
return undefined;

View File

@ -0,0 +1,20 @@
/// <reference path='fourslash.ts' />
////const f = /*a*/(param) => {
//// return {
//// "a": 1,
//// "b": 2,
//// }[param];
////}/*b*/;
goTo.select("a", "b");
edit.applyRefactor({
refactorName: "Add or remove braces in an arrow function",
actionName: "Remove braces from arrow function",
actionDescription: "Remove braces from arrow function",
newContent:
`const f = (param) => ({
"a": 1,
"b": 2,
}[param]);`,
});