Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions packages/eslint-plugin/src/rules/no-unnecessary-type-assertion.ts
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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,
},
],
},
],
});