Skip to content

Commit

Permalink
feat(eslint-plugin): [no-extra-!-assert] flag ?. after !-assert (#1460)
Browse files Browse the repository at this point in the history
  • Loading branch information
a-tarasyuk authored and bradzacher committed Jan 16, 2020
1 parent 9f9a5c5 commit 58c7c25
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 3 deletions.
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,
},
],
},
],
});

0 comments on commit 58c7c25

Please sign in to comment.