Skip to content
Merged
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
4 changes: 4 additions & 0 deletions src/compiler/diagnosticMessages.json
Original file line number Diff line number Diff line change
Expand Up @@ -5140,6 +5140,10 @@
"category": "Message",
"code": 95092
},
"Convert 'const' to 'let'": {
"category": "Message",
"code": 95093
},

"No value exists in scope for the shorthand property '{0}'. Either declare one or provide an initializer.": {
"category": "Error",
Expand Down
32 changes: 32 additions & 0 deletions src/services/codefixes/convertConstToLet.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/* @internal */
namespace ts.codefix {
const fixId = "fixConvertConstToLet";
const errorCodes = [Diagnostics.Cannot_assign_to_0_because_it_is_a_constant.code];

registerCodeFix({
errorCodes,
getCodeActions: context => {
const { sourceFile, span, program } = context;
const variableStatement = getVariableStatement(sourceFile, span.start, program);
const changes = textChanges.ChangeTracker.with(context, t => doChange(t, sourceFile, variableStatement));
return [createCodeFixAction(fixId, changes, Diagnostics.Convert_const_to_let, fixId, Diagnostics.Convert_const_to_let)];
},
fixIds: [fixId]
});

function getVariableStatement(sourceFile: SourceFile, pos: number, program: Program) {
const token = getTokenAtPosition(sourceFile, pos);
const checker = program.getTypeChecker();
const symbol = checker.getSymbolAtLocation(token);
if (symbol) {
return symbol.valueDeclaration.parent.parent as VariableStatement;
}
}
function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, variableStatement?: VariableStatement) {
if (!variableStatement) {
return;
}
const start = variableStatement.getStart();
changes.replaceRangeWithText(sourceFile, { pos: start, end: start + 5 }, "let");
}
}
1 change: 1 addition & 0 deletions src/services/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@
"codefixes/fixAddModuleReferTypeMissingTypeof.ts",
"codefixes/convertToMappedObjectType.ts",
"codefixes/removeUnnecessaryAwait.ts",
"codefixes/convertConstToLet.ts",
"refactors/convertExport.ts",
"refactors/convertImport.ts",
"refactors/extractSymbol.ts",
Expand Down
12 changes: 12 additions & 0 deletions tests/cases/fourslash/codeFixConstToLet.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/// <reference path='fourslash.ts' />

//// const x = 42;
//// x = 75;

verify.codeFix({
description: "Convert 'const' to 'let'",
index: 0,
newFileContent:
`let x = 42;
x = 75;`
});