• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/* @internal */
2namespace ts.codefix {
3    const fixId = "fixNoPropertyAccessFromIndexSignature";
4    const errorCodes = [
5        Diagnostics.Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0.code
6    ];
7
8    registerCodeFix({
9        errorCodes,
10        fixIds: [fixId],
11        getCodeActions(context) {
12            const { sourceFile, span, preferences } = context;
13            const property = getPropertyAccessExpression(sourceFile, span.start);
14            const changes = textChanges.ChangeTracker.with(context, t => doChange(t, context.sourceFile, property, preferences));
15            return [createCodeFixAction(fixId, changes, [Diagnostics.Use_element_access_for_0, property.name.text], fixId, Diagnostics.Use_element_access_for_all_undeclared_properties)];
16        },
17        getAllCodeActions: context =>
18            codeFixAll(context, errorCodes, (changes, diag) => doChange(changes, diag.file, getPropertyAccessExpression(diag.file, diag.start), context.preferences))
19    });
20
21    function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, node: PropertyAccessExpression, preferences: UserPreferences): void {
22        const quotePreference = getQuotePreference(sourceFile, preferences);
23        const argumentsExpression = factory.createStringLiteral(node.name.text, quotePreference === QuotePreference.Single);
24        changes.replaceNode(
25            sourceFile,
26            node,
27            isPropertyAccessChain(node) ?
28                factory.createElementAccessChain(node.expression, node.questionDotToken, argumentsExpression) :
29                factory.createElementAccessExpression(node.expression, argumentsExpression)
30        );
31    }
32
33    function getPropertyAccessExpression(sourceFile: SourceFile, pos: number): PropertyAccessExpression {
34        return cast(getTokenAtPosition(sourceFile, pos).parent, isPropertyAccessExpression);
35    }
36}
37