Tslint: Rule request: empty-constructor

Created on 10 Jan 2018  路  8Comments  路  Source: palantir/tslint

TypeScript code being linted

class Counter {
    private count: number = 0;

    public constructor() { }

    public increase(): number {
        return this.count += 1;
    }
}

Actual behavior

No complaints under tslint:recommended.

Expected behavior

The constructor does nothing and should be removed. There's no complaint saying this.

Folks new to classes / TypeScript will sometimes add constructors because they think they're necessary no matter what.

P2 Accepting PRs Rule Suggestion

Most helpful comment

And what about the following example? Isn't it unnecessary as well?

constructor() {
    super();
}

All 8 comments

Another thing to look out for as an option (should just initialize via private count: number = 0;):

class Counter {
    private count: number;

    public constructor() {
        this.count = 0;
    }

    public increase(): number {
        return this.count += 1;
    }
}

@JoshuaKGoldberg isn't this covered by [tslint] block is empty [no-empty] rule anyway?

@vpanjganj technically yes, but not everybody enables no-empty.

And what about the following example? Isn't it unnecessary as well?

constructor() {
    super();
}

@asmironov yup, that's correct!

@asmironov @JoshuaKGoldberg isnt something like this unnecessary as well?

constructor(requiredParam: string) {
    super(requiredParam);
}

Ah, this rule was added in #3647. It only handles the case of a constructor with an empty body.

@Bublade that's correct! If you'd like to file a new issue, that'd be great.

@JoshuaKGoldberg It seems like a +6 yrs concern since #67 馃
As mentioned in the old issue, to get around this, you can add an empty comment

constructor() {
  //
}

For new devs who write in TypeScript and came across this comment, just listen to @JoshuaKGoldberg 's tip, and delete "empty" constructor, if it's empty, then you don't need it, and removing redundant stuff is a great benefit we get by using a linter. Do NOT try to skip/ignore/stop every linting rule to "pass" it!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ghost picture ghost  路  3Comments

jacob-robertson picture jacob-robertson  路  3Comments

DanielKucal picture DanielKucal  路  3Comments

rajinder-yadav picture rajinder-yadav  路  3Comments

dashmug picture dashmug  路  3Comments