sindresorhus/eslint-plugin-unicorn

Rule proposal: Require declaring class members upfront

クローズ

#990 opened on 2021/01/02

 (9 件のコメント) (1 件のリアクション) (0 人の担当者)JavaScript (468 件のフォーク)user submission
help wantednew rule

Repository metrics

Stars
 (5,022 個のスター)
PR merge metrics
 (平均マージ 4h 30m) (30d で 26 merged PRs)

説明

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

コントリビューターガイド