🧘

TypeScript 狂信者のための ESLint rules 〜 null/undefined check 編

に公開

目的

  • TypeScript は非常によい言語だが、残念なことに nullundefined という空値を表す値が2つもある。
  • これらを巡って血で血を洗う宗教戦争が続いているが、今ここで争いに終止符を打つ。
  • 長年欲しかった lint rule を ChatGPT 神が啓示してくれたので福音伝道する。

TL;DR

全て a == null または a != null で統一しなさい。

以下を eslintrc に書き込むだけ。 ("eslint": "8.57.0" 以上で動作確認済み)

"no-restricted-syntax": [
  {
    "message": "Avoid using '=== null'. Use '== null' to check for both null and undefined.",
    "selector": "BinaryExpression[operator='==='][right.type='Literal'][right.value=null]",
  },
  {
    "message": "Avoid using '!== null'. Use '!= null' to check for both null and undefined.",
    "selector": "BinaryExpression[operator='!=='][right.type='Literal'][right.value=null]",
  },
  {
    "message": "Avoid using '=== undefined'. Use '== null' to check for both null and undefined.",
    "selector": "BinaryExpression[operator='==='][right.type='Identifier'][right.name='undefined']",
  },
  {
    "message": "Avoid using '!== undefined'. Use '!= null' to check for both null and undefined.",
    "selector": "BinaryExpression[operator='!=='][right.type='Identifier'][right.name='undefined']",
  },
],

Bad👎

a === null
a !== null
a === undefined
a !== undefined

Good✅

a == null
a != null

逆方向 (e.g. null === a) を書くやつはさすがに見たことがないのでやってないが、やりたくば応用してできるだろう。

eqeqeq との併用

以下も設定すればよい。

"eqeqeq": [
  2,
  "always",
  {
    "null": "ignore",
  },
],

なぜ

神は言っている、a == null または a != null だけ使えと。

Null vs. Undefined | TypeScript Deep Dive (日本語版)

Recommend == null to check for both undefined or null. You generally don't want to make a distinction between the two.

== nullを使ってundefinedと nullを両方ともチェックすることを推奨します。一般的に2つを区別する必要はありません。

You could also do == undefined, but == null is more conventional/shorter.

I personally don't care to distinguish between the two as most projects use libraries with differing opinions and just rule out both with == null.

== nullで除外するだけなので、2つの区別について気にすることはありません。

Exactly(そのとおりでございます)
例えば === null して undefined だけ通して Uncaught TypeError: Cannot read properties of null にしたいケースがあるか?
つまりそういうことだ。

Discussion