diff --git a/src/services/organizeImports.ts b/src/services/organizeImports.ts index 9c504357102..c2a7ea180bb 100644 --- a/src/services/organizeImports.ts +++ b/src/services/organizeImports.ts @@ -28,12 +28,12 @@ namespace ts.OrganizeImports { organizeImportsWorker(topLevelExportDecls, coalesceExports); for (const ambientModule of sourceFile.statements.filter(isAmbientModule)) { - const ambientModuleBody = getModuleBlock(ambientModule as ModuleDeclaration)!; // TODO: GH#18217 + if (!ambientModule.body) { continue; } - const ambientModuleImportDecls = ambientModuleBody.statements.filter(isImportDeclaration); + const ambientModuleImportDecls = ambientModule.body.statements.filter(isImportDeclaration); organizeImportsWorker(ambientModuleImportDecls, coalesceAndOrganizeImports); - const ambientModuleExportDecls = ambientModuleBody.statements.filter(isExportDeclaration); + const ambientModuleExportDecls = ambientModule.body.statements.filter(isExportDeclaration); organizeImportsWorker(ambientModuleExportDecls, coalesceExports); } @@ -81,11 +81,6 @@ namespace ts.OrganizeImports { } } - function getModuleBlock(moduleDecl: ModuleDeclaration): ModuleBlock | undefined { - const body = moduleDecl.body; - return body && !isIdentifier(body) ? (isModuleBlock(body) ? body : getModuleBlock(body)) : undefined; - } - function removeUnusedImports(oldImports: ReadonlyArray, sourceFile: SourceFile, program: Program) { const typeChecker = program.getTypeChecker(); const jsxNamespace = typeChecker.getJsxNamespace(); diff --git a/src/testRunner/unittests/services/organizeImports.ts b/src/testRunner/unittests/services/organizeImports.ts index 1421780a4b4..d3fe55f9686 100644 --- a/src/testRunner/unittests/services/organizeImports.ts +++ b/src/testRunner/unittests/services/organizeImports.ts @@ -274,6 +274,16 @@ export const Other = 1; assert.isEmpty(changes); }); + it("doesn't crash on shorthand ambient module", () => { + const testFile = { + path: "/a.ts", + content: "declare module '*';", + }; + const languageService = makeLanguageService(testFile); + const changes = languageService.organizeImports({ type: "file", fileName: testFile.path }, testFormatSettings, emptyOptions); + assert.isEmpty(changes); + }); + testOrganizeImports("Renamed_used", { path: "/test.ts",