diff --git a/src/services/refactors/extractMethod.ts b/src/services/refactors/extractMethod.ts index ac1c8383efa2a..9634b9c817281 100644 --- a/src/services/refactors/extractMethod.ts +++ b/src/services/refactors/extractMethod.ts @@ -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 { @@ -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); diff --git a/tests/cases/fourslash/extract-method-not-for-import.ts b/tests/cases/fourslash/extract-method-not-for-import.ts new file mode 100644 index 0000000000000..a72d793611d62 --- /dev/null +++ b/tests/cases/fourslash/extract-method-not-for-import.ts @@ -0,0 +1,10 @@ +/// + +// @Filename: /a.ts +////i/**/mport _ from "./b"; + +// @Filename: /b.ts +////export default function f() {} + +goTo.marker(""); +verify.not.refactorAvailable('Extract Method');