Home > Software design >  Eslint, no useless constructor with super() inside?
Eslint, no useless constructor with super() inside?

Time:02-19

code:

  constructor(cdr: ChangeDetectorRef, inj: Injector) {
    super(cdr, inj);
  }

eslint:

 {
   ...
   overrides: {
      ...
      rules: {
        ...
        "@typescript-eslint/no-useless-constructor": "error",
        ...
      }
   }
}

This rule is telling me to remove useless constructor, but I must call super() inside.

How can I bypass this rule without disabling or removing it?

CodePudding user response:

Just remove the constructor. It's not necessary to define it if you have no further use. For your extended class, it's the same as an empty constructor. It's useless since it's automatically handled by JavaScript/TypeScript. See docs.

If you don't provide your own constructor, then a default constructor will be supplied for you. ... If your class is a derived class, the default constructor calls the parent constructor, passing along any arguments that were provided.

So yes constructors for derived classes must contain a super call. But you don't necessarily have to define an empty constructor or just super inside (derived classes). Unless you want to add more or different signature.

If you still want to keep it, just remove/disable the linter rule.

There is a Caveat to know:

This lint rule will report on constructors whose sole purpose is to change visibility of a parent constructor. -- TS Docs also see ES Docs

  • Related