-
Notifications
You must be signed in to change notification settings - Fork 12.8k
/
Copy pathfixNoPropertyAccessFromIndexSignature.ts
52 lines (48 loc) · 2.15 KB
/
fixNoPropertyAccessFromIndexSignature.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import {
codeFixAll,
createCodeFixAction,
registerCodeFix,
} from "../_namespaces/ts.codefix.js";
import {
cast,
Diagnostics,
factory,
getQuotePreference,
getTokenAtPosition,
isPropertyAccessChain,
isPropertyAccessExpression,
PropertyAccessExpression,
QuotePreference,
SourceFile,
textChanges,
UserPreferences,
} from "../_namespaces/ts.js";
const fixId = "fixNoPropertyAccessFromIndexSignature";
const errorCodes = [
Diagnostics.Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0.code,
];
registerCodeFix({
errorCodes,
fixIds: [fixId],
getCodeActions(context) {
const { sourceFile, span, preferences } = context;
const property = getPropertyAccessExpression(sourceFile, span.start);
const changes = textChanges.ChangeTracker.with(context, t => doChange(t, context.sourceFile, property, preferences));
return [createCodeFixAction(fixId, changes, [Diagnostics.Use_element_access_for_0, property.name.text], fixId, Diagnostics.Use_element_access_for_all_undeclared_properties)];
},
getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => doChange(changes, diag.file, getPropertyAccessExpression(diag.file, diag.start), context.preferences)),
});
function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, node: PropertyAccessExpression, preferences: UserPreferences): void {
const quotePreference = getQuotePreference(sourceFile, preferences);
const argumentsExpression = factory.createStringLiteral(node.name.text, quotePreference === QuotePreference.Single);
changes.replaceNode(
sourceFile,
node,
isPropertyAccessChain(node) ?
factory.createElementAccessChain(node.expression, node.questionDotToken, argumentsExpression) :
factory.createElementAccessExpression(node.expression, argumentsExpression),
);
}
function getPropertyAccessExpression(sourceFile: SourceFile, pos: number): PropertyAccessExpression {
return cast(getTokenAtPosition(sourceFile, pos).parent, isPropertyAccessExpression);
}