@@ -5,19 +5,29 @@ namespace ts.codefix {
5
5
registerCodeFix ( {
6
6
errorCodes,
7
7
getCodeActions : function getCodeActionsToAddConvertToUnknownForNonOverlappingTypes ( context ) {
8
- const changes = textChanges . ChangeTracker . with ( context , t => makeChange ( t , context . sourceFile , context . span . start ) ) ;
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 ) ) ;
9
11
return [ createCodeFixAction ( fixId , changes , Diagnostics . Add_unknown_conversion_for_non_overlapping_types , fixId , Diagnostics . Add_unknown_to_all_conversions_of_non_overlapping_types ) ] ;
10
12
} ,
11
13
fixIds : [ fixId ] ,
12
- getAllCodeActions : context => codeFixAll ( context , errorCodes , ( changes , diag ) => makeChange ( changes , diag . file , diag . start ) ) ,
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
+ } ) ,
13
20
} ) ;
14
21
15
- function makeChange ( changeTracker : textChanges . ChangeTracker , sourceFile : SourceFile , pos : number ) {
16
- const token = getTokenAtPosition ( sourceFile , pos ) ;
17
- const assertion = Debug . checkDefined ( findAncestor ( token , ( n ) : n is AsExpression | TypeAssertion => isAsExpression ( n ) || isTypeAssertionExpression ( n ) ) , "Expected to find an assertion expression" ) ;
22
+ function makeChange ( changeTracker : textChanges . ChangeTracker , sourceFile : SourceFile , assertion : AsExpression | TypeAssertion ) {
18
23
const replacement = isAsExpression ( assertion )
19
24
? factory . createAsExpression ( assertion . expression , factory . createKeywordTypeNode ( SyntaxKind . UnknownKeyword ) )
20
25
: factory . createTypeAssertion ( factory . createKeywordTypeNode ( SyntaxKind . UnknownKeyword ) , assertion . expression ) ;
21
26
changeTracker . replaceNode ( sourceFile , assertion . expression , replacement ) ;
22
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
+ }
23
33
}
0 commit comments