Skip to content

[WIP] Invalid quick fix for class that's exported as a variable with isolatedDeclarations #61855

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

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
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
145 changes: 102 additions & 43 deletions src/services/codefixes/fixMissingTypeAnnotationOnExports.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import {
createCodeFixAction,
createCombinedCodeActions,
createImportAdder,
eachDiagnostic,
registerCodeFix,
typeNodeToAutoImportableTypeNode,
typePredicateToAutoImportableTypeNode,
typeToMinimizedReferenceType,
import {
createCodeFixAction,
createCombinedCodeActions,
createImportAdder,
eachDiagnostic,
ImportAdder,
importSymbols,
registerCodeFix,
tryGetAutoImportableReferenceFromTypeNode,
typePredicateToAutoImportableTypeNode,
typeToMinimizedReferenceType,
} from "../_namespaces/ts.codefix.js";
import {
ArrayBindingPattern,
Expand Down Expand Up @@ -38,15 +40,17 @@
findAncestor,
FunctionDeclaration,
GeneratedIdentifierFlags,
getEmitScriptTarget,
getSourceFileOfNode,
getSynthesizedDeepClone,
getTokenAtPosition,
getEmitScriptTarget,
getNameForExportedSymbol,
getSourceFileOfNode,
getSynthesizedDeepClone,
getTokenAtPosition,
getTrailingCommentRanges,
hasInitializer,
hasSyntacticModifier,
Identifier,
InternalNodeBuilderFlags,
Identifier,
ImportDeclaration,
InternalNodeBuilderFlags,
isArrayBindingPattern,
isArrayLiteralExpression,
isAssertionExpression,
Expand Down Expand Up @@ -80,16 +84,19 @@
isValueSignatureDeclaration,
isVariableDeclaration,
ModifierFlags,
ModifierLike,
Node,
ModifierLike,
NamedImports,

Check warning on line 88 in src/services/codefixes/fixMissingTypeAnnotationOnExports.ts

View workflow job for this annotation

GitHub Actions / lint

'NamedImports' is defined but never used. Allowed unused vars must match /^(_+$|_[^_])/u
NamespaceImport,

Check warning on line 89 in src/services/codefixes/fixMissingTypeAnnotationOnExports.ts

View workflow job for this annotation

GitHub Actions / lint

'NamespaceImport' is defined but never used. Allowed unused vars must match /^(_+$|_[^_])/u
Node,
NodeBuilderFlags,
NodeFlags,
ObjectBindingPattern,
ObjectLiteralExpression,
ParameterDeclaration,
PropertyAccessExpression,
PropertyDeclaration,
setEmitFlags,
PropertyDeclaration,
ScriptTarget,
setEmitFlags,
SignatureDeclaration,
some,
SourceFile,
Expand Down Expand Up @@ -1097,22 +1104,22 @@
return emptyInferenceResult;
}

function typeToTypeNode(type: Type, enclosingDeclaration: Node, flags = NodeBuilderFlags.None): TypeNode | undefined {
let isTruncated = false;
const minimizedTypeNode = typeToMinimizedReferenceType(typeChecker, type, enclosingDeclaration, declarationEmitNodeBuilderFlags | flags, declarationEmitInternalNodeBuilderFlags, {
moduleResolverHost: program,
trackSymbol() {
return true;
},
reportTruncationError() {
isTruncated = true;
},
});
if (!minimizedTypeNode) {
return undefined;
}
const result = typeNodeToAutoImportableTypeNode(minimizedTypeNode, importAdder, scriptTarget);
return isTruncated ? factory.createKeywordTypeNode(SyntaxKind.AnyKeyword) : result;
function typeToTypeNode(type: Type, enclosingDeclaration: Node, flags = NodeBuilderFlags.None): TypeNode | undefined {
let isTruncated = false;
const minimizedTypeNode = typeToMinimizedReferenceType(typeChecker, type, enclosingDeclaration, declarationEmitNodeBuilderFlags | flags, declarationEmitInternalNodeBuilderFlags, {
moduleResolverHost: program,
trackSymbol() {
return true;
},
reportTruncationError() {
isTruncated = true;
},
});
if (!minimizedTypeNode) {
return undefined;
}
const result = typeNodeToAutoImportableTypeNodeWithExistingImportCheck(minimizedTypeNode, importAdder, scriptTarget, sourceFile, typeChecker);
return isTruncated ? factory.createKeywordTypeNode(SyntaxKind.AnyKeyword) : result;
}

function typePredicateToTypeNode(typePredicate: TypePredicate, enclosingDeclaration: Node, flags = NodeBuilderFlags.None): TypeNode | undefined {
Expand Down Expand Up @@ -1142,14 +1149,66 @@
}
}

function typeToStringForDiag(node: Node) {
setEmitFlags(node, EmitFlags.SingleLine);
const result = typePrinter.printNode(EmitHint.Unspecified, node, sourceFile);
if (result.length > defaultMaximumTruncationLength) {
return result.substring(0, defaultMaximumTruncationLength - "...".length) + "...";
}
setEmitFlags(node, EmitFlags.None);
return result;
function typeToStringForDiag(node: Node) {
setEmitFlags(node, EmitFlags.SingleLine);
const result = typePrinter.printNode(EmitHint.Unspecified, node, sourceFile);
if (result.length > defaultMaximumTruncationLength) {
return result.substring(0, defaultMaximumTruncationLength - "...".length) + "...";
}
setEmitFlags(node, EmitFlags.None);
return result;
}

function typeNodeToAutoImportableTypeNodeWithExistingImportCheck(typeNode: TypeNode, importAdder: ImportAdder, scriptTarget: ScriptTarget, sourceFile: SourceFile, typeChecker: TypeChecker): TypeNode | undefined {
const importableReference = tryGetAutoImportableReferenceFromTypeNode(typeNode, scriptTarget);
if (importableReference) {
// Check if symbols are already available before importing them
const symbolsToImport = importableReference.symbols.filter(symbol => {
const symbolName = getNameForExportedSymbol(symbol, scriptTarget);
return !isSymbolAlreadyAvailable(symbolName, sourceFile, typeChecker);
});

if (symbolsToImport.length > 0) {
importSymbols(importAdder, symbolsToImport);
}
typeNode = importableReference.typeNode;
}

// Ensure nodes are fresh so they can have different positions when going through formatting.
return getSynthesizedDeepClone(typeNode);
}

function isSymbolAlreadyAvailable(symbolName: string, sourceFile: SourceFile, _typeChecker: TypeChecker): boolean {
// Check if the symbol name is already imported in the current file
for (const statement of sourceFile.statements) {
if (statement.kind === SyntaxKind.ImportDeclaration) {
const importDecl = statement as ImportDeclaration;
if (importDecl.importClause) {
// Check default import
if (importDecl.importClause.name && importDecl.importClause.name.text === symbolName) {
return true;
}
// Check named imports
if (importDecl.importClause.namedBindings && importDecl.importClause.namedBindings.kind === SyntaxKind.NamedImports) {
const namedImports = importDecl.importClause.namedBindings;
for (const element of namedImports.elements) {
const name = element.name.text;
if (name === symbolName) {
return true;
}
}
}
// Check namespace import
if (importDecl.importClause.namedBindings && importDecl.importClause.namedBindings.kind === SyntaxKind.NamespaceImport) {
const namespaceImport = importDecl.importClause.namedBindings;
if (namespaceImport.name.text === symbolName) {
return true;
}
}
}
}
}
return false;
}

// Some --isolatedDeclarations errors are not present on the node that directly needs type annotation, so look in the
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/// <reference path='fourslash.ts'/>

// @isolatedDeclarations: true
// @declaration: true

// @fileName: mymodule.d.ts
////declare class VolumeClass {
//// constructor();
////}
////export const Volume: typeof VolumeClass;

// @fileName: test.ts
////import { Volume } from './mymodule';
////export const foo = new Volume();

verify.codeFixAll({
fixId: "fixMissingTypeAnnotationOnExports",
fixAllDescription: ts.Diagnostics.Add_all_missing_type_annotations.message,
newFileContent:
`import { Volume } from './mymodule';
export const foo: Volume = new Volume();`
});
Loading