• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/* @internal */
2namespace ts.codefix {
3    const fixId = "fixConvertConstToLet";
4    const errorCodes = [Diagnostics.Cannot_assign_to_0_because_it_is_a_constant.code];
5
6    registerCodeFix({
7        errorCodes,
8        getCodeActions: context => {
9            const { sourceFile, span, program } = context;
10            const variableStatement = getVariableStatement(sourceFile, span.start, program);
11            const changes = textChanges.ChangeTracker.with(context, t => doChange(t, sourceFile, variableStatement));
12            return [createCodeFixAction(fixId, changes, Diagnostics.Convert_const_to_let, fixId, Diagnostics.Convert_const_to_let)];
13        },
14        fixIds: [fixId]
15    });
16
17    function getVariableStatement(sourceFile: SourceFile, pos: number, program: Program) {
18        const token = getTokenAtPosition(sourceFile, pos);
19        const checker = program.getTypeChecker();
20        const symbol = checker.getSymbolAtLocation(token);
21        if (symbol) {
22            return symbol.valueDeclaration.parent.parent as VariableStatement;
23        }
24    }
25    function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, variableStatement?: VariableStatement) {
26        if (!variableStatement) {
27            return;
28        }
29        const start = variableStatement.getStart();
30        changes.replaceRangeWithText(sourceFile, { pos: start, end: start + 5 }, "let");
31    }
32}
33