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

+15-9
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

+16
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)