sindresorhus/eslint-plugin-unicorn

Do you want to work on this issue?

You can request for a bounty in order to promote it!

Rule proposal: `prefer-class-fields` #314

MrHen posted onGitHub

There is a superior pattern for class field declarations that can declutter constructors (often making them totally unnecessary.) The feature is still considered experimental but it works out of the box with babel.

Fail:

class Foo {
  constructor() {
    this.foo = 'foo';
  }
}

Pass:

class Foo {
  foo = 'foo';
}

Sounds good, but I think we should wait until ESLint supports class fields.


Should it also handle:

class Foo {
  constructor() {
    this._foo = 'foo';
  }
}

to

class Foo {
  #foo = 'foo';
}

?

posted by sindresorhus over 5 years ago

I think a rule for private fields would be awesome, yeah. I don't think we can realistically auto-fix those, however, because people abuse _foo access too regularly and it would very quickly break code.

posted by MrHen over 5 years ago

So you think private fields should be a separate rule?


I don't think we can realistically auto-fix those, however, because people abuse _foo access too regularly and it would very quickly break code.

šŸ‘

posted by sindresorhus over 5 years ago

Yeah. As a general principle, I prefer rules to be have the smallest reasonable scope.

In this case, I can also see why a team might want to convert to class fields because of the fixer but not want to enable the private fields rule right away because they'd have to move a bunch of code around.

posted by MrHen over 5 years ago
posted by sindresorhus about 4 years ago

Does ESLint support class fields yet?

posted by sindresorhus about 4 years ago

Does ESLint support class fields yet?

It does now

This rule would be pretty useful on Error constructors like:

class MyError extends Error {
  constructor(message: string) {
    super(message);
    this.name = "MyError";
  }
}

šŸ‘‡

class MyError extends Error {
  name = "MyError"
}
posted by fregante about 3 years ago

This is accepted.

posted by sindresorhus about 3 years ago

bump

posted by jimmywarting over 1 year ago

@fregante has funded $30.00 to this issue.


posted by issuehunt-oss[bot] 11 months ago

FYI I've implemented this rule here, feel free to review & comment!

posted by FRSgit about 2 months ago

Fund this Issue

$30.00
Funded
Only logged in users can fund an issue

Pull requests

Recent activities

fregante funded 30.00 for sindresorhus/eslint-plugin-unicorn# 314
11 months ago