sindresorhus/eslint-plugin-unicorn

Rule proposal: Require declaring class members upfront

Chiusa

#990 aperta il 2 gen 2021

 (9 commenti) (1 reazione) (0 assegnatari)JavaScript (468 fork)user submission
help wantednew rule

Metriche repository

Star
 (5022 stelle)
Metriche merge PR
 (Merge medio 1g 16h) (399 PR mergiate in 30 g)

Descrizione

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
	}
}

Guida contributor