Skip to content
← Back to rules

typescript/no-unnecessary-condition Nursery

💭 This rule requires type information.

何をするか

TypeScript の型情報に基づいて、常に真値、常に偽値、または常に nullish となる条件を禁止する。

なぜ問題なのか

実行時に変化のない条件は、コードの読みにくさを招き、論理エラーを隠す可能性がある。このような条件はしばしば到達不可能な分岐(デッドコード)を残し、宣言された型と意図した振る舞いが一致していないことを示唆する。

このルールに対して 不正 なコードの例:

ts
declare const value: null;
if (value) {
  doWork();
}

const items: string[] = [];
if (items) {
  doWork();
}

declare const status: "ready";
if (!status) {
  reportError();
}

このルールに対して 正しい コードの例:

ts
declare const maybeUser: User | undefined;
if (maybeUser) {
  doWork(maybeUser);
}

const items: string[] = [];
if (items.length > 0) {
  doWork();
}

declare const status: "ready" | "";
if (!status) {
  reportError();
}

設定

このルールは以下のプロパティを持つ設定オブジェクトを受け入れます。

allowConstantLoopConditions

type: boolean | "never" | "always" | "only-allowed-literals"

JSON で allowConstantLoopConditions が指定される可能性のあるさまざまな方法を表す。以下が可能:

  • true または false
  • 文字列の列挙型("never""always""only-allowed-literals"

checkTypePredicates

type: boolean

default: false

型述語関数のチェックを行うかどうか。

使用方法

このルールを 有効化 するには、設定ファイルまたは CLI で次のように使用できます:

json
{
  "rules": {
    "typescript/no-unnecessary-condition": "error"
  }
}
bash
oxlint --type-aware --deny typescript/no-unnecessary-condition

参照