Skip to content
This repository was archived by the owner on Mar 25, 2021. It is now read-only.

Commit 613c311

Browse files
ericbfJosh Goldberg
authored andcommitted
Check for non-public modifiers in constructors (#4511) (#4619)
This commit checks the modifiers of each constructor declaration. If it has any modifier that isn't `public`, then it's actually necessary and shouldn't be flagged by unnecessary-constructor rule.
1 parent e544769 commit 613c311

File tree

2 files changed

+18
-11
lines changed

2 files changed

+18
-11
lines changed

src/rules/unnecessaryConstructorRule.ts

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -45,22 +45,23 @@ export class Rule extends Lint.Rules.AbstractRule {
4545
const isEmptyConstructor = (node: ts.ConstructorDeclaration): boolean =>
4646
node.body !== undefined && node.body.statements.length === 0;
4747

48-
const containsConstructorParameter = (node: ts.ConstructorDeclaration): boolean => {
49-
for (const parameter of node.parameters) {
50-
if (isParameterProperty(parameter)) {
51-
return true;
52-
}
53-
}
48+
const containsConstructorParameter = (node: ts.ConstructorDeclaration): boolean =>
49+
// If this has any parameter properties
50+
node.parameters.some(isParameterProperty);
5451

55-
return false;
56-
};
52+
const isAccessRestrictingConstructor = (node: ts.ConstructorDeclaration): boolean =>
53+
// No modifiers implies public
54+
node.modifiers != undefined &&
55+
// If this has any modifier that isn't public, it's doing something
56+
node.modifiers.some(modifier => modifier.kind !== ts.SyntaxKind.PublicKeyword);
5757

5858
function walk(context: Lint.WalkContext) {
5959
const callback = (node: ts.Node): void => {
6060
if (
6161
isConstructorDeclaration(node) &&
6262
isEmptyConstructor(node) &&
63-
!containsConstructorParameter(node)
63+
!containsConstructorParameter(node) &&
64+
!isAccessRestrictingConstructor(node)
6465
) {
6566
context.addFailureAtNode(node, Rule.FAILURE_STRING);
6667
} else {

test/rules/unnecessary-constructor/test.ts.lint

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,10 @@ class PublicConstructor {
1010

1111
class ProtectedConstructor {
1212
protected constructor() { }
13-
~~~~~~~~~~~~~~~~~~~~~~~~~~~ [0]
1413
}
1514

1615
class PrivateConstructor {
1716
private constructor() { }
18-
~~~~~~~~~~~~~~~~~~~~~~~~~ [0]
1917
}
2018

2119
class SameLine { constructor() { } }
@@ -55,6 +53,14 @@ class ContainsParameter {
5553
~~~~~~~~~~~~~~~~~~~~~~~~~~ [0]
5654
}
5755

56+
class PrivateContainsParameter {
57+
private constructor(x: number) { }
58+
}
59+
60+
class ProtectedContainsParameter {
61+
protected constructor(x: number) { }
62+
}
63+
5864
class ContainsParameterDeclaration {
5965
constructor(public x: number) { }
6066
}

0 commit comments

Comments
 (0)