Skip to content

Don't try to extract import to a method: simpler fix #18054

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 15 additions & 11 deletions src/services/refactors/extractMethod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -232,17 +232,7 @@ namespace ts.refactor.extractMethod {
return { errors };
}

// If our selection is the expression in an ExpressionStatement, expand
// the selection to include the enclosing Statement (this stops us
// from trying to care about the return value of the extracted function
// and eliminates double semicolon insertion in certain scenarios)
const range = isStatement(start)
? [start]
: start.parent && start.parent.kind === SyntaxKind.ExpressionStatement
? [start.parent as Statement]
: start as Expression;

return { targetRange: { range, facts: rangeFacts, declarations } };
return { targetRange: { range: getStatementOrExpressionRange(start), facts: rangeFacts, declarations } };
}

function createErrorResult(sourceFile: SourceFile, start: number, length: number, message: DiagnosticMessage): RangeToExtract {
Expand Down Expand Up @@ -459,6 +449,20 @@ namespace ts.refactor.extractMethod {
}
}

function getStatementOrExpressionRange(node: Node): Statement[] | Expression {
if (isStatement(node)) {
return [node];
}
else if (isPartOfExpression(node)) {
// If our selection is the expression in an ExpressionStatement, expand
// the selection to include the enclosing Statement (this stops us
// from trying to care about the return value of the extracted function
// and eliminates double semicolon insertion in certain scenarios)
return isExpressionStatement(node.parent) ? [node.parent] : node as Expression;
}
return undefined;
}

function isValidExtractionTarget(node: Node): node is Scope {
// Note that we don't use isFunctionLike because we don't want to put the extracted closure *inside* a method
return (node.kind === SyntaxKind.FunctionDeclaration) || isSourceFile(node) || isModuleBlock(node) || isClassLike(node);
Expand Down
10 changes: 10 additions & 0 deletions tests/cases/fourslash/extract-method-not-for-import.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/// <reference path='fourslash.ts' />

// @Filename: /a.ts
////i/**/mport _ from "./b";

// @Filename: /b.ts
////export default function f() {}

goTo.marker("");
verify.not.refactorAvailable('Extract Method');