Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(eslint-plugin): [no-unnecessary-type-assertion] handle assignment #3133

Merged
merged 1 commit into from Mar 8, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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,
},
],
},
],
});