Skip to content

Commit aea4216

Browse files
author
Murad Khan
committed
Added fixConvertConstToLet.ts with preliminary fix, needs improved diagnostic messages
1 parent 9aeb6e2 commit aea4216

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/* @internal */
2+
namespace ts.codefix {
3+
const fixId = "fixConvertConstToLet";
4+
const errorCodes = [
5+
Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property.code
6+
];
7+
8+
registerCodeFix({
9+
errorCodes,
10+
getCodeActions(context) {
11+
const { sourceFile, span } = context;
12+
const { declaration, kind } = getDeclaration(sourceFile, span.start);
13+
if (!declaration) return undefined;
14+
15+
const changes = textChanges.ChangeTracker.with(context, t => doChange(t, sourceFile, node, kind));
16+
return [createCodeFixAction(fixId, changes, Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, fixId, Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property)];
17+
},
18+
fixIds: [fixId],
19+
getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => {
20+
const { kind, declaration } = getDeclaration(diag.file, diag.start, context);
21+
if (declaration) doChange(changes, context.sourceFile, declaration, kind);
22+
}),
23+
});
24+
25+
function getDeclaration(sourceFile: SourceFile, pos: number, context: CodeFixContextBase): {declaration: Node, kind: SyntaxKind} {
26+
const node = getTokenAtPosition(sourceFile, pos);
27+
let declaration: Node;
28+
let kind: SyntaxKind;
29+
if (isVarConst(node)) {
30+
declaration = findAncestor(node, isVariableDeclaration);
31+
kind = SyntaxKind.ConstKeyword;
32+
} else if (hasReadOnlyModifier(node)) {
33+
declaration = findAncestor(node, isPropertyDeclaration);
34+
kind = SyntaxKind.ReadonlyKeyword;
35+
}
36+
return { kind, declaration };
37+
}
38+
39+
function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, node: Node, kind: SyntaxKind) {
40+
if (kind === SyntaxKind.ConstKeyword) {
41+
let letNode: Node = createNode(SyntaxKind.LetKeyword, node.getStart(), node.getEnd(), node.parent);
42+
changes.replaceNode(sourceFile, node, letNode);
43+
} else if (kind === SyntaxKind.ReadonlyKeyword) {
44+
// let
45+
}
46+
}
47+
}

0 commit comments

Comments
 (0)