• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/* @internal */
2namespace ts.codefix {
3    const fixId = "addConvertToUnknownForNonOverlappingTypes";
4    const errorCodes = [Diagnostics.Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first.code];
5    registerCodeFix({
6        errorCodes,
7        getCodeActions: function getCodeActionsToAddConvertToUnknownForNonOverlappingTypes(context) {
8            const assertion = getAssertion(context.sourceFile, context.span.start);
9            if (assertion === undefined) return undefined;
10            const changes = textChanges.ChangeTracker.with(context, t => makeChange(t, context.sourceFile, assertion));
11            return [createCodeFixAction(fixId, changes, Diagnostics.Add_unknown_conversion_for_non_overlapping_types, fixId, Diagnostics.Add_unknown_to_all_conversions_of_non_overlapping_types)];
12        },
13        fixIds: [fixId],
14        getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => {
15            const assertion = getAssertion(diag.file, diag.start);
16            if (assertion) {
17                makeChange(changes, diag.file, assertion);
18            }
19        }),
20    });
21
22    function makeChange(changeTracker: textChanges.ChangeTracker, sourceFile: SourceFile, assertion: AsExpression | TypeAssertion) {
23        const replacement = isAsExpression(assertion)
24            ? factory.createAsExpression(assertion.expression, factory.createKeywordTypeNode(SyntaxKind.UnknownKeyword))
25            : factory.createTypeAssertion(factory.createKeywordTypeNode(SyntaxKind.UnknownKeyword), assertion.expression);
26        changeTracker.replaceNode(sourceFile, assertion.expression, replacement);
27    }
28
29    function getAssertion(sourceFile: SourceFile, pos: number): AsExpression | TypeAssertion | undefined {
30        if (isInJSFile(sourceFile)) return undefined;
31        return findAncestor(getTokenAtPosition(sourceFile, pos), (n): n is AsExpression | TypeAssertion => isAsExpression(n) || isTypeAssertionExpression(n));
32    }
33}
34