Infer extracted local variable name from property name (#37902)

This commit is contained in:
Thai Pangsakulyanont
2022-03-18 03:39:13 +07:00
committed by GitHub
parent df1faa09b8
commit 9a2868bf98
10 changed files with 60 additions and 1 deletions

View File

@@ -1136,7 +1136,9 @@ namespace ts.refactor.extractSymbol {
// Make a unique name for the extracted variable
const file = scope.getSourceFile();
const localNameText = getUniqueName(isClassLike(scope) ? "newProperty" : "newLocal", file);
const localNameText = isPropertyAccessExpression(node) && !isClassLike(scope) && !checker.resolveName(node.name.text, node, SymbolFlags.Value, /*excludeGlobals*/ false) && !isPrivateIdentifier(node.name) && !isKeyword(node.name.originalKeywordKind!)
? node.name.text
: getUniqueName(isClassLike(scope) ? "newProperty" : "newLocal", file);
const isJS = isInJSFile(scope);
let variableType = isJS || !checker.isContextSensitive(node)

View File

@@ -279,6 +279,19 @@ switch (1) {
break;
}
`);
testExtractConstant("extractConstant_PropertyName",
`[#|x.y|].z();`);
testExtractConstant("extractConstant_PropertyName_ExistingName",
`let y;
[#|x.y|].z();`);
testExtractConstant("extractConstant_PropertyName_Keyword",
`[#|x.if|].z();`);
testExtractConstant("extractConstant_PropertyName_PrivateIdentifierKeyword",
`[#|this.#if|].z();`);
});
function testExtractConstant(caption: string, text: string) {

View File

@@ -0,0 +1,5 @@
// ==ORIGINAL==
/*[#|*/x.y/*|]*/.z();
// ==SCOPE::Extract to constant in enclosing scope==
const y = x.y;
/*RENAME*/y.z();

View File

@@ -0,0 +1,5 @@
// ==ORIGINAL==
/*[#|*/x.y/*|]*/.z();
// ==SCOPE::Extract to constant in enclosing scope==
const y = x.y;
/*RENAME*/y.z();

View File

@@ -0,0 +1,7 @@
// ==ORIGINAL==
let y;
/*[#|*/x.y/*|]*/.z();
// ==SCOPE::Extract to constant in enclosing scope==
let y;
const newLocal = x.y;
/*RENAME*/newLocal.z();

View File

@@ -0,0 +1,7 @@
// ==ORIGINAL==
let y;
/*[#|*/x.y/*|]*/.z();
// ==SCOPE::Extract to constant in enclosing scope==
let y;
const newLocal = x.y;
/*RENAME*/newLocal.z();

View File

@@ -0,0 +1,5 @@
// ==ORIGINAL==
/*[#|*/x.if/*|]*/.z();
// ==SCOPE::Extract to constant in enclosing scope==
const newLocal = x.if;
/*RENAME*/newLocal.z();

View File

@@ -0,0 +1,5 @@
// ==ORIGINAL==
/*[#|*/x.if/*|]*/.z();
// ==SCOPE::Extract to constant in enclosing scope==
const newLocal = x.if;
/*RENAME*/newLocal.z();

View File

@@ -0,0 +1,5 @@
// ==ORIGINAL==
/*[#|*/this.#if/*|]*/.z();
// ==SCOPE::Extract to constant in enclosing scope==
const newLocal = this.#if;
/*RENAME*/newLocal.z();

View File

@@ -0,0 +1,5 @@
// ==ORIGINAL==
/*[#|*/this.#if/*|]*/.z();
// ==SCOPE::Extract to constant in enclosing scope==
const newLocal = this.#if;
/*RENAME*/newLocal.z();