diff --git a/src/services/refactors/convertStringOrTemplateLiteral.ts b/src/services/refactors/convertStringOrTemplateLiteral.ts index e8b8768362c..b926ce65f28 100644 --- a/src/services/refactors/convertStringOrTemplateLiteral.ts +++ b/src/services/refactors/convertStringOrTemplateLiteral.ts @@ -12,8 +12,9 @@ namespace ts.refactor.convertStringOrTemplateLiteral { function getAvailableActions(context: RefactorContext): ReadonlyArray { const { file, startPosition } = context; - const node = getTokenAtPosition(file, startPosition); - const maybeBinary = getParentBinaryExpression(node); containsString(maybeBinary); + let node = getTokenAtPosition(file, startPosition); + if (isParenthesizedExpression(node.parent) && isBinaryExpression(node.parent.parent)) node = node.parent.parent; + const maybeBinary = getParentBinaryExpression(node); const maybeTemplateExpression = findAncestor(node, n => isTemplateExpression(n)); const actions: RefactorActionInfo[] = []; @@ -30,11 +31,13 @@ namespace ts.refactor.convertStringOrTemplateLiteral { function getEditsForAction(context: RefactorContext, actionName: string): RefactorEditInfo | undefined { const { file, startPosition } = context; - const node = getTokenAtPosition(file, startPosition); + let node = getTokenAtPosition(file, startPosition); switch (actionName) { case toTemplateLiteralActionName: + if (isParenthesizedExpression(node.parent) && isBinaryExpression(node.parent.parent)) node = node.parent.parent; const maybeBinary = getParentBinaryExpression(node); + const arrayOfNodes = treeToArray(maybeBinary)[0]; const templateLiteral = nodesToTemplate(arrayOfNodes); const edits = textChanges.ChangeTracker.with(context, t => t.replaceNode(file, maybeBinary, templateLiteral)); @@ -78,15 +81,6 @@ namespace ts.refactor.convertStringOrTemplateLiteral { return expr; } - function containsString(node: Node): boolean { - if (isBinaryExpression(node)) { - return containsString(node.left) || containsString(node.right); - } - - if (isStringLiteral(node)) return true; - return false; - } - function arrayToTree(nodes: Expression[], bexpr: BinaryExpression | undefined): BinaryExpression { if (nodes.length === 0) return bexpr!; diff --git a/tests/cases/fourslash/refactorConvertStringOrTemplateLiteral_ToTemplateExprFromBrace.ts b/tests/cases/fourslash/refactorConvertStringOrTemplateLiteral_ToTemplateExprFromBrace.ts new file mode 100644 index 00000000000..5924da73ebc --- /dev/null +++ b/tests/cases/fourslash/refactorConvertStringOrTemplateLiteral_ToTemplateExprFromBrace.ts @@ -0,0 +1,12 @@ +/// + +//// const foo = "foobar is " + /*x*/(/*y*/42 + 6) + " years old" + +goTo.select("x", "y"); +edit.applyRefactor({ + refactorName: "Convert string concatenation or template literal", + actionName: "Convert to template literal", + actionDescription: "Convert to template literal", + newContent: +`const foo = \`foobar is \${42 + 6} years old\``, +});