跳转到内容

noUselessConstructor

Diagnostic Category: lint/complexity/noUselessConstructor

Since: v1.0.0

Sources:

Disallow unnecessary constructors.

ES2015 provides a default class constructor if one is not specified. As such, providing an empty constructor or one that delegates into its parent is unnecessary.

The rule ignores:

  • decorated classes;
  • constructors with at least one parameter property;
  • private and protected constructors.

This rule reports on constructors whose sole purpose is to make a parent constructor public. See the last invalid example.

class A {
constructor (a) {}
}
code-block.js:2:5 lint/complexity/noUselessConstructor  FIXABLE  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

This constructor is unnecessary.

1 │ class A {
> 2 │ constructor (a) {}
^^^^^^^^^^^^^^^^^^
3 │ }
4 │

Unsafe fix: Remove the unnecessary constructor.

1 1 class A {
2 - ····constructor·(a)·{}
3 2 }
4 3

class B extends A {
constructor (a) {
super(a);
}
}
code-block.ts:2:5 lint/complexity/noUselessConstructor  FIXABLE  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

This constructor is unnecessary.

1 │ class B extends A {
> 2 │ constructor (a) {
^^^^^^^^^^^^^^^^^
> 3 │ super(a);
> 4 │ }
^
5 │ }
6 │

Unsafe fix: Remove the unnecessary constructor.

1 1 class B extends A {
2 - ····constructor·(a)·{
3 - ········super(a);
4 - ····}
5 2 }
6 3

class C {
/**
* Documented constructor.
*/
constructor () {}
}
code-block.js:5:5 lint/complexity/noUselessConstructor  FIXABLE  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

This constructor is unnecessary.

3 │ * Documented constructor.
4 │ */
> 5 │ constructor () {}
^^^^^^^^^^^^^^^^^
6 │ }
7 │

Unsafe fix: Remove the unnecessary constructor.

1 1 class C {
2 - ····/**
3 - ·····*·Documented·constructor.
4 - ·····*/
5 - ····constructor·()·{}
6 2 }
7 3

class A {
protected constructor() {
this.prop = 1;
}
}
class B extends A {
// Make the parent constructor public.
constructor () {
super();
}
}
code-block.js:2:5 parse ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

‘protected’ modifier can only be used in TypeScript files

1 │ class A {
> 2 │ protected constructor() {
^^^^^^^^^
3 │ this.prop = 1;
4 │ }

class A {
constructor (prop) {
this.prop = prop;
}
}
class B extends A {
constructor () {
super(5);
}
}
class C {
// Empty constructor with parameter properties are allowed.
constructor (private prop: number) {}
}
class D {
constructor(public arg: number){}
}
class F extends D {
// constructor with default parameters are allowed.
constructor(arg = 4) {
super(arg)
}
}
@Decorator
class C {
constructor (prop: number) {}
}