Skip to main content

no-unsafe-enum-comparison

Disallow comparing an enum value with a non-enum value.

💡

此规则报告的一些问题可以通过编辑器 建议 手动修复。

💭

该规则需要 类型信息 才能运行。


在处理枚举时,TypeScript 编译器可能出奇地宽松。 字符串枚举被广泛认为比数字枚举更安全,但即使字符串枚举也有一些缺陷。 例如,允许将枚举值与字面量进行比较:

英:The TypeScript compiler can be surprisingly lenient when working with enums. String enums are widely considered to be safer than number enums, but even string enums have some pitfalls. For example, it is allowed to compare enum values against literals:

enum Vegetable {
Asparagus = 'asparagus',
}

declare const vegetable: Vegetable;

vegetable === 'asparagus'; // No error

上面的代码片段应该写成 vegetable === Vegetable.Asparagus。 允许比较中的字面量首先就颠覆了使用枚举的意义。 通过强制与正确类型的枚举进行比较:

英:The above code snippet should instead be written as vegetable === Vegetable.Asparagus. Allowing literals in comparisons subverts the point of using enums in the first place. By enforcing comparisons with properly typed enums:

  • 它使代码库对枚举成员更改值更具弹性。
  • 它允许代码 IDE 使用 "重命名符号" 功能快速重命名枚举。
  • 它将代码与正确的枚举语义对齐,即通过名称引用它们并将它们的值视为实现细节。
.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/no-unsafe-enum-comparison": "error"
}
};
在线运行试试这个规则 ↗

示例

enum Fruit {
Apple,
}

declare let fruit: Fruit;

fruit === 0;
Open in Playground
enum Vegetable {
Asparagus = 'asparagus',
}

declare let vegetable: Vegetable;

vegetable === 'asparagus';
Open in Playground

何时不使用它

如果你不介意将数字和/或字面量字符串常量与枚举进行比较,则可能不需要此规则。

英:If you don't mind number and/or literal string constants being compared against enums, you likely don't need this rule.

另外,在极少数依赖仅作为 type 导入的第三方枚举的情况下,可能很难遵守此规则。 你可以考虑在这些特定情况下使用 ESLint 禁用注释,而不是完全禁用此规则。

英:Separately, in the rare case of relying on an third party enums that are only imported as types, it may be difficult to adhere to this rule. You might consider using ESLint disable comments for those specific situations instead of completely disabling this rule.

选项

该规则不可配置。

资源