Skip to content
← Back to rules

typescript/no-unsafe-enum-comparison Suspicious

💭 This rule requires type information.
🚧 An auto-fix is planned for this rule, but not implemented at this time.

何をしますか

このルールは、列挙型の値と非列挙型の値を比較することを禁止します。

なぜ問題なのか

列挙型の値は、同じ列挙型の他の値またはその基底となるリテラル値と、安全な型で比較すべきです。関係のない値と列挙型を比較すると、予期しない動作が発生し、型安全性のために列挙型を使用する目的を無効にしてしまいます。

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

ts
enum Status {
  Open = "open",
  Closed = "closed",
}

enum Color {
  Red = "red",
  Blue = "blue",
}

declare const status: Status;
declare const color: Color;
declare const str: string;

// 異なる列挙型と比較
if (status === color) {
} // 安全でない

// 文字列と比較(リテラルが一致する場合を除く)
if (status === str) {
} // 安全でない

// 任意の値と比較
if (status === "unknown") {
} // 安全でない

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

ts
enum Status {
  Open = "open",
  Closed = "closed",
}

declare const status: Status;

// 同じ列挙型の値と比較
if (status === Status.Open) {
} // 安全

// 正しいリテラル型と比較
if (status === "open") {
} // 安全

// 列挙型メソッドの使用
if (Object.values(Status).includes(someValue)) {
} // 検証する安全な方法

使用方法

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

json
{
  "rules": {
    "typescript/no-unsafe-enum-comparison": "error"
  }
}
bash
oxlint --type-aware --deny typescript/no-unsafe-enum-comparison

参照