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

feat(eslint-plugin): [no-extra-non-null-assertion] flag optional chain after a non-null assertion #1460

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
12 changes: 12 additions & 0 deletions packages/eslint-plugin/docs/rules/no-extra-non-null-assertion.md
Expand Up @@ -15,6 +15,12 @@ function foo(bar: number | undefined) {
}
```

```ts
function foo(bar?: { n: number }) {
return bar!?.n;
}
```

Examples of **correct** code for this rule:

```ts
Expand All @@ -28,6 +34,12 @@ function foo(bar: number | undefined) {
}
```

```ts
function foo(bar?: { n: number }) {
return bar?.n;
}
```

## How to use

```json
Expand Down
12 changes: 9 additions & 3 deletions packages/eslint-plugin/src/rules/no-extra-non-null-assertion.ts
@@ -1,4 +1,5 @@
import * as util from '../util';
import { TSESTree } from '@typescript-eslint/experimental-utils';

export default util.createRule({
name: 'no-extra-non-null-assertion',
Expand All @@ -16,10 +17,15 @@ export default util.createRule({
},
defaultOptions: [],
create(context) {
function checkExtraNonNullAssertion(
node: TSESTree.TSNonNullExpression,
): void {
context.report({ messageId: 'noExtraNonNullAssertion', node });
}

return {
'TSNonNullExpression > TSNonNullExpression'(node): void {
context.report({ messageId: 'noExtraNonNullAssertion', node });
},
'TSNonNullExpression > TSNonNullExpression': checkExtraNonNullAssertion,
'OptionalMemberExpression > TSNonNullExpression': checkExtraNonNullAssertion,
};
},
});
Expand Up @@ -19,6 +19,13 @@ function foo(bar: number | undefined) {
const bar: number = bar!;
} `,
},
{
code: `
function foo(bar?: { n: number }) {
return bar?.n;
}
`,
},
],
invalid: [
{
Expand Down Expand Up @@ -62,5 +69,47 @@ function foo(bar: number | undefined) {
},
],
},
{
code: `
function foo(bar?: { n: number }) {
return bar!?.n;
}
`,
errors: [
{
messageId: 'noExtraNonNullAssertion',
endColumn: 14,
column: 10,
line: 3,
},
],
},
{
code: `
function foo(bar?: { n: number }) {
return bar!!!?.n;
}
`,
errors: [
{
messageId: 'noExtraNonNullAssertion',
endColumn: 16,
column: 10,
line: 3,
},
{
messageId: 'noExtraNonNullAssertion',
endColumn: 15,
column: 10,
line: 3,
},
{
messageId: 'noExtraNonNullAssertion',
endColumn: 14,
column: 10,
line: 3,
},
],
},
],
});