@@ -5,19 +5,29 @@ namespace ts.codefix {
55 registerCodeFix ( {
66 errorCodes,
77 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 ) ) ;
911 return [ createCodeFixAction ( fixId , changes , Diagnostics . Add_unknown_conversion_for_non_overlapping_types , fixId , Diagnostics . Add_unknown_to_all_conversions_of_non_overlapping_types ) ] ;
1012 } ,
1113 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+ } ) ,
1320 } ) ;
1421
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 ) {
1823 const replacement = isAsExpression ( assertion )
1924 ? factory . createAsExpression ( assertion . expression , factory . createKeywordTypeNode ( SyntaxKind . UnknownKeyword ) )
2025 : factory . createTypeAssertion ( factory . createKeywordTypeNode ( SyntaxKind . UnknownKeyword ) , assertion . expression ) ;
2126 changeTracker . replaceNode ( sourceFile , assertion . expression , replacement ) ;
2227 }
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+ }
2333}
0 commit comments