Skip to content

Commit

Permalink
feat(eslint-plugin): [no-unnecessary-type-assertion] use getContextua…
Browse files Browse the repository at this point in the history
…lType directly
  • Loading branch information
Zzzen committed Mar 2, 2021
1 parent 3e204e9 commit 97e184c
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 33 deletions.
33 changes: 0 additions & 33 deletions packages/eslint-plugin/src/util/types.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,8 @@
import debug from 'debug';
import {
isCallExpression,
isJsxExpression,
isIdentifier,
isNewExpression,
isParameterDeclaration,
isPropertyDeclaration,
isTypeReference,
isUnionOrIntersectionType,
isVariableDeclaration,
unionTypeParts,
isPropertyAssignment,
} from 'tsutils';
import * as ts from 'typescript';

Expand Down Expand Up @@ -483,30 +475,5 @@ export function getContextualType(
return;
}

if (isCallExpression(parent) || isNewExpression(parent)) {
if (node === parent.expression) {
// is the callee, so has no contextual type
return;
}
} else if (
isVariableDeclaration(parent) ||
isPropertyDeclaration(parent) ||
isParameterDeclaration(parent)
) {
return parent.type ? checker.getTypeFromTypeNode(parent.type) : undefined;
} else if (isJsxExpression(parent)) {
return checker.getContextualType(parent);
} else if (isPropertyAssignment(parent) && isIdentifier(node)) {
return checker.getContextualType(node);
} else if (
![ts.SyntaxKind.TemplateSpan, ts.SyntaxKind.JsxExpression].includes(
parent.kind,
)
) {
// parent is not something we know we can get the contextual type of
return;
}
// TODO - support return statement checking

return checker.getContextualType(node);
}
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,41 @@ const c = <const>[...a, ...b];
{
code: "const a = <const>{ foo: 'foo' };",
},
{
code: `
let a: number | undefined;
let b: number | undefined;
a = b;
a != b;
a == !b;
a! != b!;
a! != b;
`,
},
{
code: `
function num(): number {
let n: number | undefined;
return n!;
}
`,
},
{
code: `
function num() {
let n: number | undefined;
return n!;
}
`,
},
{
code: `
async function num(): Promise<number> {
let n: Promise<number> | undefined;
return n!;
}
`,
},
],

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

0 comments on commit 97e184c

Please sign in to comment.