Skip to content

Commit

Permalink
fix(eslint-plugin): [no-unnec-type-assert] handle JSX attributes (#1002)
Browse files Browse the repository at this point in the history
Co-authored-by: Armano <armano2@users.noreply.github.com>
  • Loading branch information
bradzacher and armano2 committed Jan 13, 2020
1 parent 4ee1a25 commit 3c5659b
Show file tree
Hide file tree
Showing 5 changed files with 51 additions and 1 deletion.
@@ -1,6 +1,7 @@
import { TSESTree } from '@typescript-eslint/experimental-utils';
import {
isCallExpression,
isJsxExpression,
isNewExpression,
isObjectType,
isObjectFlagSet,
Expand Down Expand Up @@ -117,6 +118,8 @@ export default util.createRule<Options, MessageIds>({
return parent.type
? checker.getTypeFromTypeNode(parent.type)
: undefined;
} else if (isJsxExpression(parent)) {
return checker.getContextualType(parent);
} else if (
![ts.SyntaxKind.TemplateSpan, ts.SyntaxKind.JsxExpression].includes(
parent.kind,
Expand Down
1 change: 1 addition & 0 deletions packages/eslint-plugin/tests/RuleTester.ts
Expand Up @@ -44,6 +44,7 @@ class RuleTester extends TSESLint.RuleTester {
): void {
const errorMessage = `Do not set the parser at the test level unless you want to use a parser other than ${parser}`;

// standardize the valid tests as objects
tests.valid = tests.valid.map(test => {
if (typeof test === 'string') {
return {
Expand Down
Empty file.
7 changes: 6 additions & 1 deletion packages/eslint-plugin/tests/fixtures/tsconfig.json
@@ -1,10 +1,15 @@
{
"compilerOptions": {
"jsx": "preserve",
"target": "es5",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"lib": ["es2015", "es2017", "esnext"],
"experimentalDecorators": true
}
},
"include": [
"file.ts",
"react.tsx"
]
}
Expand Up @@ -117,6 +117,19 @@ function testFunction(_param: string | null): void { /* noop */ }
const value = 'test' as string | null | undefined
testFunction(value!)
`,
// https://github.com/typescript-eslint/typescript-eslint/issues/982
{
code: `
declare namespace JSX { interface IntrinsicElements { div: { key?: string | number } } }
function Test(props: {
id?: null | string | number;
}) {
return <div key={props.id!} />;
}
`,
filename: path.join(rootDir, 'react.tsx'),
},
],

invalid: [
Expand Down Expand Up @@ -327,5 +340,33 @@ class Mx {
},
],
},
// https://github.com/typescript-eslint/typescript-eslint/issues/982
{
code: `
declare namespace JSX { interface IntrinsicElements { div: { key?: string | number } } }
function Test(props: {
id?: string | number;
}) {
return <div key={props.id!} />;
}
`,
output: `
declare namespace JSX { interface IntrinsicElements { div: { key?: string | number } } }
function Test(props: {
id?: string | number;
}) {
return <div key={props.id} />;
}
`,
errors: [
{
messageId: 'contextuallyUnnecessary',
line: 7,
},
],
filename: path.join(rootDir, 'react.tsx'),
},
],
});

0 comments on commit 3c5659b

Please sign in to comment.