sindresorhus/eslint-plugin-unicorn

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 about 6 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 about 6 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 about 6 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 about 6 years ago
posted by sindresorhus over 4 years ago

Does ESLint support class fields yet?

posted by sindresorhus over 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 over 3 years ago

This is accepted.

posted by sindresorhus over 3 years ago

bump

posted by jimmywarting almost 2 years ago

@fregante has funded $30.00 to this issue.


posted by issuehunt-oss[bot] over 1 year ago

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

posted by FRSgit 8 months ago

@sindresorhus has rewarded $27.00 to @frsgit. See it on IssueHunt

  • :moneybag: Total deposit: $30.00
  • :tada: Repository reward(0%): $0.00
  • :wrench: Service fee(10%): $3.00
posted by issuehunt-oss[bot] 2 months ago

Fund this Issue

$30.00
Rewarded

Rewarded pull request

Recent activities