Skip to content

Commit

Permalink
fix(eslint-plugin): [no-unnecessary-type-assertion] handle assignment (
Browse files Browse the repository at this point in the history
  • Loading branch information
Zzzen committed Mar 8, 2021
1 parent 3f9e9a1 commit cb22561
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 0 deletions.
19 changes: 19 additions & 0 deletions packages/eslint-plugin/src/rules/no-unnecessary-type-assertion.ts
Expand Up @@ -135,7 +135,26 @@ export default util.createRule<Options, MessageIds>({

return {
TSNonNullExpression(node): void {
if (
node.parent?.type === AST_NODE_TYPES.AssignmentExpression &&
node.parent?.operator === '=' &&
node.parent.left === node
) {
context.report({
node,
messageId: 'contextuallyUnnecessary',
fix(fixer) {
return fixer.removeRange([
node.expression.range[1],
node.range[1],
]);
},
});
return;
}

const originalNode = parserServices.esTreeNodeToTSNodeMap.get(node);

const type = util.getConstrainedTypeAtLocation(
checker,
originalNode.expression,
Expand Down
8 changes: 8 additions & 0 deletions packages/eslint-plugin/src/util/types.ts
Expand Up @@ -11,6 +11,7 @@ import {
isVariableDeclaration,
unionTypeParts,
isPropertyAssignment,
isBinaryExpression,
} from 'tsutils';
import * as ts from 'typescript';

Expand Down Expand Up @@ -498,6 +499,13 @@ export function getContextualType(
return checker.getContextualType(parent);
} else if (isPropertyAssignment(parent) && isIdentifier(node)) {
return checker.getContextualType(node);
} else if (
isBinaryExpression(parent) &&
parent.operatorToken.kind === ts.SyntaxKind.EqualsToken &&
parent.right === node
) {
// is RHS of assignment
return checker.getTypeAtLocation(parent.left);
} else if (
![ts.SyntaxKind.TemplateSpan, ts.SyntaxKind.JsxExpression].includes(
parent.kind,
Expand Down
Expand Up @@ -186,6 +186,22 @@ const c = <const>[...a, ...b];
{
code: "const a = <const>{ foo: 'foo' };",
},
{
code: `
let a: number | undefined;
let b: number | undefined;
let c: number;
a = b;
c = b!;
a! -= 1;
`,
},
{
code: `
let a: { b?: string } | undefined;
a!.b = '';
`,
},
],

invalid: [
Expand Down Expand Up @@ -451,5 +467,29 @@ function Test(props: { id?: string | number }) {
],
filename: 'react.tsx',
},
{
code: `
let x: number | undefined;
let y: number | undefined;
y = x!;
y! = 0;
`,
output: `
let x: number | undefined;
let y: number | undefined;
y = x;
y = 0;
`,
errors: [
{
messageId: 'contextuallyUnnecessary',
line: 4,
},
{
messageId: 'contextuallyUnnecessary',
line: 5,
},
],
},
],
});

0 comments on commit cb22561

Please sign in to comment.