From 3de706a8525c2ded782fc032fa4afe2e485100d3 Mon Sep 17 00:00:00 2001 From: Andrew Branch Date: Mon, 26 Apr 2021 11:52:34 -0700 Subject: [PATCH] =?UTF-8?q?Don=E2=80=99t=20create=20invalid=20type-only=20?= =?UTF-8?q?imports=20during=20add=20missing=20import=20(#43828)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/services/codefixes/importFixes.ts | 3 ++ .../fourslash/importNameCodeFix_typeOnly3.ts | 34 +++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 tests/cases/fourslash/importNameCodeFix_typeOnly3.ts diff --git a/src/services/codefixes/importFixes.ts b/src/services/codefixes/importFixes.ts index 364c8c3c7f6..061aeaaca77 100644 --- a/src/services/codefixes/importFixes.ts +++ b/src/services/codefixes/importFixes.ts @@ -420,6 +420,9 @@ namespace ts.codefix { const { importClause } = declaration; if (!importClause || !isStringLiteralLike(declaration.moduleSpecifier)) return undefined; const { name, namedBindings } = importClause; + // A type-only import may not have both a default and named imports, so the only way a name can + // be added to an existing type-only import is adding a named import to existing named bindings. + if (importClause.isTypeOnly && !(importKind === ImportKind.Named && namedBindings)) return undefined; return importKind === ImportKind.Default && !name || importKind === ImportKind.Named && (!namedBindings || namedBindings.kind === SyntaxKind.NamedImports) ? { kind: ImportFixKind.AddToExisting, importClauseOrBindingPattern: importClause, importKind, moduleSpecifier: declaration.moduleSpecifier.text, canUseTypeOnlyImport } : undefined; diff --git a/tests/cases/fourslash/importNameCodeFix_typeOnly3.ts b/tests/cases/fourslash/importNameCodeFix_typeOnly3.ts new file mode 100644 index 00000000000..0c51cb2b9df --- /dev/null +++ b/tests/cases/fourslash/importNameCodeFix_typeOnly3.ts @@ -0,0 +1,34 @@ +/// + +// @importsNotUsedAsValues: error + +// @Filename: Presenter.ts +//// export type DisplayStyle = "normal" | "compact"; +//// +//// export default class Presenter { +//// present(displayStyle: DisplayStyle): Element { +//// return document.createElement("placeholder"); +//// } +//// } + +// @Filename: index.ts +//// import type Presenter from "./Presenter"; +//// +//// function present( +//// presenter: Presenter, +//// displayStyle: DisplayStyle, +//// ) {} + +goTo.file("index.ts"); +verify.codeFix({ + errorCode: ts.Diagnostics.Cannot_find_name_0.code, + description: ignoreInterpolations(ts.Diagnostics.Import_0_from_module_1), + newFileContent: +`import type { DisplayStyle } from "./Presenter"; +import type Presenter from "./Presenter"; + +function present( + presenter: Presenter, + displayStyle: DisplayStyle, +) {}` +});