Skip to content

Commit

Permalink
feat(eslint-plugin): [no-empty-function] new allow option overrideMet…
Browse files Browse the repository at this point in the history
…hods (#4923)
  • Loading branch information
Josh-Cena committed May 16, 2022
1 parent 04a216c commit 13c05ae
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 2 deletions.
19 changes: 18 additions & 1 deletion packages/eslint-plugin/docs/rules/no-empty-function.md
Expand Up @@ -28,7 +28,8 @@ This rule adds the following options:
type AdditionalAllowOptionEntries =
| 'private-constructors'
| 'protected-constructors'
| 'decoratedFunctions';
| 'decoratedFunctions'
| 'overrideMethods';

type AllowOptionEntries =
| BaseNoEmptyFunctionAllowOptionEntries
Expand Down Expand Up @@ -77,6 +78,22 @@ class Foo {
}
```

### allow: `overrideMethods`

Examples of correct code for the `{ "allow": ["overrideMethods"] }` option:

```ts
abstract class Base {
protected greet(): void {
console.log('Hello!');
}
}

class Foo extends Base {
protected override greet(): void {}
}
```

## How to Use

```jsonc
Expand Down
16 changes: 15 additions & 1 deletion packages/eslint-plugin/src/rules/no-empty-function.ts
Expand Up @@ -30,6 +30,7 @@ const schema = util.deepMerge(
'asyncFunctions',
'asyncMethods',
'decoratedFunctions',
'overrideMethods',
],
},
},
Expand Down Expand Up @@ -63,6 +64,7 @@ export default util.createRule<Options, MessageIds>({
);
const isAllowedPrivateConstructors = allow.includes('private-constructors');
const isAllowedDecoratedFunctions = allow.includes('decoratedFunctions');
const isAllowedOverrideMethods = allow.includes('overrideMethods');

/**
* Check if the method body is empty
Expand Down Expand Up @@ -138,12 +140,24 @@ export default util.createRule<Options, MessageIds>({
return false;
}

function isAllowedEmptyOverrideMethod(
node: TSESTree.FunctionExpression,
): boolean {
return (
isAllowedOverrideMethods &&
isBodyEmpty(node) &&
node.parent?.type === AST_NODE_TYPES.MethodDefinition &&
node.parent.override === true
);
}

return {
...rules,
FunctionExpression(node): void {
if (
isAllowedEmptyConstructor(node) ||
isAllowedEmptyDecoratedFunctions(node)
isAllowedEmptyDecoratedFunctions(node) ||
isAllowedEmptyOverrideMethod(node)
) {
return;
}
Expand Down
25 changes: 25 additions & 0 deletions packages/eslint-plugin/tests/rules/no-empty-function.test.ts
Expand Up @@ -72,6 +72,14 @@ class Foo {
`,
options: [{ allow: ['decoratedFunctions'] }],
},
{
code: `
class Foo extends Base {
override foo() {}
}
`,
options: [{ allow: ['overrideMethods'] }],
},
],

invalid: [
Expand Down Expand Up @@ -192,5 +200,22 @@ class Foo {
},
],
},
{
code: `
class Foo extends Base {
override foo() {}
}
`,
errors: [
{
messageId: 'unexpected',
data: {
name: "method 'foo'",
},
line: 3,
column: 18,
},
],
},
],
});

0 comments on commit 13c05ae

Please sign in to comment.