Skip to content

Commit 0221476

Browse files
author
Josh Goldberg
authored
fix(eslint-plugin): always ignore assignments in no-unnecessary-type-assertion (typescript-eslint#3235)
1 parent b1b26c4 commit 0221476

File tree

2 files changed

+24
-17
lines changed

2 files changed

+24
-17
lines changed

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

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -137,19 +137,24 @@ export default util.createRule<Options, MessageIds>({
137137
TSNonNullExpression(node): void {
138138
if (
139139
node.parent?.type === AST_NODE_TYPES.AssignmentExpression &&
140-
node.parent?.operator === '=' &&
141-
node.parent.left === node
140+
node.parent.operator === '='
142141
) {
143-
context.report({
144-
node,
145-
messageId: 'contextuallyUnnecessary',
146-
fix(fixer) {
147-
return fixer.removeRange([
148-
node.expression.range[1],
149-
node.range[1],
150-
]);
151-
},
152-
});
142+
if (node.parent.left === node) {
143+
context.report({
144+
node,
145+
messageId: 'contextuallyUnnecessary',
146+
fix(fixer) {
147+
return fixer.removeRange([
148+
node.expression.range[1],
149+
node.range[1],
150+
]);
151+
},
152+
});
153+
}
154+
// for all other = assignments we ignore non-null checks
155+
// this is because non-null assertions can change the type-flow of the code
156+
// so whilst they might be unnecessary for the assignment - they are necessary
157+
// for following code
153158
return;
154159
}
155160

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

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,12 @@ let a: { b?: string } | undefined;
202202
a!.b = '';
203203
`,
204204
},
205+
`
206+
let value: number | undefined;
207+
let values: number[] = [];
208+
209+
value = values.pop()!;
210+
`,
205211
],
206212

207213
invalid: [
@@ -493,14 +499,10 @@ y! = 0;
493499
output: `
494500
let x: number | undefined;
495501
let y: number | undefined;
496-
y = x;
502+
y = x!;
497503
y = 0;
498504
`,
499505
errors: [
500-
{
501-
messageId: 'contextuallyUnnecessary',
502-
line: 4,
503-
},
504506
{
505507
messageId: 'contextuallyUnnecessary',
506508
line: 5,

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