Skip to content

Commit

Permalink
fix(eslint-plugin): always ignore assignments in no-unnecessary-type-…
Browse files Browse the repository at this point in the history
…assertion (#3235)
  • Loading branch information
Josh Goldberg committed Apr 5, 2021
1 parent b1b26c4 commit 0221476
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 17 deletions.
29 changes: 17 additions & 12 deletions packages/eslint-plugin/src/rules/no-unnecessary-type-assertion.ts
Expand Up @@ -137,19 +137,24 @@ export default util.createRule<Options, MessageIds>({
TSNonNullExpression(node): void {
if (
node.parent?.type === AST_NODE_TYPES.AssignmentExpression &&
node.parent?.operator === '=' &&
node.parent.left === node
node.parent.operator === '='
) {
context.report({
node,
messageId: 'contextuallyUnnecessary',
fix(fixer) {
return fixer.removeRange([
node.expression.range[1],
node.range[1],
]);
},
});
if (node.parent.left === node) {
context.report({
node,
messageId: 'contextuallyUnnecessary',
fix(fixer) {
return fixer.removeRange([
node.expression.range[1],
node.range[1],
]);
},
});
}
// for all other = assignments we ignore non-null checks
// this is because non-null assertions can change the type-flow of the code
// so whilst they might be unnecessary for the assignment - they are necessary
// for following code
return;
}

Expand Down
Expand Up @@ -202,6 +202,12 @@ let a: { b?: string } | undefined;
a!.b = '';
`,
},
`
let value: number | undefined;
let values: number[] = [];
value = values.pop()!;
`,
],

invalid: [
Expand Down Expand Up @@ -493,14 +499,10 @@ y! = 0;
output: `
let x: number | undefined;
let y: number | undefined;
y = x;
y = x!;
y = 0;
`,
errors: [
{
messageId: 'contextuallyUnnecessary',
line: 4,
},
{
messageId: 'contextuallyUnnecessary',
line: 5,
Expand Down

0 comments on commit 0221476

Please sign in to comment.