Merge pull request #18926 from amcasey/ExtractConstantArrow

Disallow constant extraction into expression-bodied arrow functions
This commit is contained in:
Andrew Casey
2017-10-03 14:29:01 -07:00
committed by GitHub
6 changed files with 61 additions and 0 deletions

View File

@@ -214,6 +214,14 @@ const x = [#|2 + 1|];
/* About x */
const x = [#|2 + 1|];
`);
testExtractConstant("extractConstant_ArrowFunction_Block", `
const f = () => {
return [#|2 + 1|];
};`);
testExtractConstant("extractConstant_ArrowFunction_Expression",
`const f = () => [#|2 + 1|];`);
});
function testExtractConstant(caption: string, text: string) {

View File

@@ -142,6 +142,7 @@ namespace ts.refactor.extractSymbol {
export const CannotAccessVariablesFromNestedScopes = createMessage("Cannot access variables from nested scopes");
export const CannotExtractToOtherFunctionLike = createMessage("Cannot extract method to a function-like scope that is not a function");
export const CannotExtractToJSClass = createMessage("Cannot extract constant to a class scope in JS");
export const CannotExtractToExpressionArrowFunction = createMessage("Cannot extract constant to an arrow function without a block");
}
enum RangeFacts {
@@ -1299,6 +1300,10 @@ namespace ts.refactor.extractSymbol {
if (isClassLike(scope) && isInJavaScriptFile(scope)) {
constantErrors.push(createDiagnosticForNode(scope, Messages.CannotExtractToJSClass));
}
if (isArrowFunction(scope) && !isBlock(scope.body)) {
// TODO (https://github.com/Microsoft/TypeScript/issues/18924): allow this
constantErrors.push(createDiagnosticForNode(scope, Messages.CannotExtractToExpressionArrowFunction));
}
constantErrorsPerScope.push(constantErrors);
}

View File

@@ -0,0 +1,18 @@
// ==ORIGINAL==
const f = () => {
return 2 + 1;
};
// ==SCOPE::Extract to constant in enclosing scope==
const f = () => {
const newLocal = 2 + 1;
return /*RENAME*/newLocal;
};
// ==SCOPE::Extract to constant in global scope==
const newLocal = 2 + 1;
const f = () => {
return /*RENAME*/newLocal;
};

View File

@@ -0,0 +1,18 @@
// ==ORIGINAL==
const f = () => {
return 2 + 1;
};
// ==SCOPE::Extract to constant in enclosing scope==
const f = () => {
const newLocal = 2 + 1;
return /*RENAME*/newLocal;
};
// ==SCOPE::Extract to constant in global scope==
const newLocal = 2 + 1;
const f = () => {
return /*RENAME*/newLocal;
};

View File

@@ -0,0 +1,6 @@
// ==ORIGINAL==
const f = () => 2 + 1;
// ==SCOPE::Extract to constant in global scope==
const newLocal = 2 + 1;
const f = () => /*RENAME*/newLocal;

View File

@@ -0,0 +1,6 @@
// ==ORIGINAL==
const f = () => 2 + 1;
// ==SCOPE::Extract to constant in global scope==
const newLocal = 2 + 1;
const f = () => /*RENAME*/newLocal;