Proposal: Always allow type-only imports to reference .ts extensions (#54746)

This commit is contained in:
Andrew Branch
2023-07-24 16:12:38 -07:00
committed by GitHub
parent 55fcee407a
commit 2170e6c6cc
9 changed files with 271 additions and 2 deletions

View File

@@ -4908,8 +4908,13 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
}
}
else if (resolvedModule.resolvedUsingTsExtension && !shouldAllowImportingTsExtension(compilerOptions, currentSourceFile.fileName)) {
const tsExtension = Debug.checkDefined(tryExtractTSExtension(moduleReference));
error(errorNode, Diagnostics.An_import_path_can_only_end_with_a_0_extension_when_allowImportingTsExtensions_is_enabled, tsExtension);
const importOrExport =
findAncestor(location, isImportDeclaration)?.importClause ||
findAncestor(location, or(isImportEqualsDeclaration, isExportDeclaration));
if (!(importOrExport?.isTypeOnly || findAncestor(location, isImportTypeNode))) {
const tsExtension = Debug.checkDefined(tryExtractTSExtension(moduleReference));
error(errorNode, Diagnostics.An_import_path_can_only_end_with_a_0_extension_when_allowImportingTsExtensions_is_enabled, tsExtension);
}
}
if (sourceFile.symbol) {

View File

@@ -5,6 +5,7 @@ import {
arrayFrom,
CancellationToken,
cast,
changeAnyExtension,
CodeAction,
CodeFixAction,
CodeFixContextBase,
@@ -42,10 +43,13 @@ import {
getExportInfoMap,
getMeaningFromDeclaration,
getMeaningFromLocation,
getModeForUsageLocation,
getNameForExportedSymbol,
getNodeId,
getOutputExtension,
getQuoteFromPreference,
getQuotePreference,
getResolvedModule,
getSourceFileOfNode,
getSymbolId,
getTokenAtPosition,
@@ -1356,6 +1360,15 @@ function promoteFromTypeOnly(changes: textChanges.ChangeTracker, aliasDeclaratio
function promoteImportClause(importClause: ImportClause) {
changes.delete(sourceFile, getTypeKeywordOfTypeOnlyImport(importClause, sourceFile));
// Change .ts extension to .js if necessary
if (!compilerOptions.allowImportingTsExtensions) {
const moduleSpecifier = tryGetModuleSpecifierFromDeclaration(importClause.parent);
const resolvedModule = moduleSpecifier && getResolvedModule(sourceFile, moduleSpecifier.text, getModeForUsageLocation(sourceFile, moduleSpecifier));
if (resolvedModule?.resolvedUsingTsExtension) {
const changedExtension = changeAnyExtension(moduleSpecifier!.text, getOutputExtension(moduleSpecifier!.text, compilerOptions));
changes.replaceNode(sourceFile, moduleSpecifier!, factory.createStringLiteral(changedExtension));
}
}
if (convertExistingToTypeOnly) {
const namedImports = tryCast(importClause.namedBindings, isNamedImports);
if (namedImports && namedImports.elements.length > 1) {