Skip to content

Commit 265a039

Browse files
authored
fix(eslint-plugin): [no-unnecessary-type-assertion] correct bad fix for angle bracket assertion (typescript-eslint#3244)
1 parent 1b41d60 commit 265a039

File tree

2 files changed

+31
-9
lines changed

2 files changed

+31
-9
lines changed

packages/eslint-plugin/src/rules/no-unnecessary-type-assertion.ts

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -258,15 +258,21 @@ export default util.createRule<Options, MessageIds>({
258258
node,
259259
messageId: 'unnecessaryAssertion',
260260
fix(fixer) {
261-
return originalNode.kind === ts.SyntaxKind.TypeAssertionExpression
262-
? fixer.removeRange([
263-
node.range[0],
264-
node.expression.range[0] - 1,
265-
])
266-
: fixer.removeRange([
267-
node.expression.range[1] + 1,
268-
node.range[1],
269-
]);
261+
if (originalNode.kind === ts.SyntaxKind.TypeAssertionExpression) {
262+
const closingAngleBracket = sourceCode.getTokenAfter(
263+
node.typeAnnotation,
264+
);
265+
return closingAngleBracket?.value === '>'
266+
? fixer.removeRange([
267+
node.range[0],
268+
closingAngleBracket.range[1],
269+
])
270+
: null;
271+
}
272+
return fixer.removeRange([
273+
node.expression.range[1] + 1,
274+
node.range[1],
275+
]);
270276
},
271277
});
272278
}

packages/eslint-plugin/tests/rules/no-unnecessary-type-assertion.test.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -358,6 +358,22 @@ function foo<T extends string>(bar: T) {
358358
},
359359
{
360360
code: `
361+
declare const foo: Foo;
362+
const bar = <Foo>foo;
363+
`,
364+
output: `
365+
declare const foo: Foo;
366+
const bar = foo;
367+
`,
368+
errors: [
369+
{
370+
messageId: 'unnecessaryAssertion',
371+
line: 3,
372+
},
373+
],
374+
},
375+
{
376+
code: `
361377
declare function nonNull(s: string | null);
362378
let s: string | null = null;
363379
nonNull(s!);

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy