sindresorhus/eslint-plugin-unicorn
Rule proposal: Require declaring class members upfront
Closed
#990 opened on Jan 2, 2021
help wantednew rule
Repository metrics
- Stars
- (5,022 stars)
- PR merge metrics
- (Avg merge 1d 16h) (399 merged PRs in 30d)
Description
Declaring the members upfront as class fields makes code more readable and can prevent typos. We would also allow initializing in the constructor, but I think we should auto-fix to class field as it's neater.
Inspired by https://github.com/eslint/eslint/issues/11540.
Any suggestions on the rule name?
Fail
class X {
func setName(name) {
this.name = name;
}
func say() {
console.log(this.name);
}
}
Pass
class X {
name;
func setName(name) {
this.name = name;
}
func say() {
console.log(this.name);
}
}
How it would prevent typos:
class X {
name;
func setName(name) {
this.name = name;
}
func say() {
// This would have resulted in `undefined` being printed without this rule.
console.log(this.myName); // ESLint error
}
}