no-unsafe-enum-comparison
禁止将枚举值与非枚举值进行比较.
在处理枚举时,TypeScript 编译器可能出奇地宽松。虽然枚举的明显安全问题是 在 TypeScript 5.0 中已解决,但一些逻辑陷阱仍然被允许。例如,允许将枚举值与非枚举值进行比较:
¥The TypeScript compiler can be surprisingly lenient when working with enums. While overt safety problems with enums were resolved in TypeScript 5.0, some logical pitfalls remain permitted. For example, it is allowed to compare enum values against non-enum values:
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 non-enums in comparisons subverts the point of using enums in the first place.
By enforcing comparisons with properly typed enums:
-
它使代码库对枚举成员更改值更具弹性。
¥It makes a codebase more resilient to enum members changing values.
-
它允许代码 IDE 使用 "重命名符号" 功能快速重命名枚举。
¥It allows for code IDEs to use the "Rename Symbol" feature to quickly rename an enum.
-
它将代码与正确的枚举语义对齐,即通过名称引用它们并将它们的值视为实现细节。
¥It aligns code to the proper enum semantics of referring to them by name and treating their values as implementation details.
- 扁平配置
- 旧版配置
export default tseslint.config({
rules: {
"@typescript-eslint/no-unsafe-enum-comparison": "error"
}
});
module.exports = {
"rules": {
"@typescript-eslint/no-unsafe-enum-comparison": "error"
}
};
在线运行试试这个规则 ↗
示例
¥Examples
- ❌ 错误
- ✅ 正确
enum Fruit {
Apple,
}
declare let fruit: Fruit;
// bad - comparison between enum and explicit value instead of named enum member
fruit === 0;
enum Vegetable {
Asparagus = 'asparagus',
}
declare let vegetable: Vegetable;
// bad - comparison between enum and explicit value instead of named enum member
vegetable === 'asparagus';
declare let anyString: string;
// bad - comparison between enum and non-enum value
anyString === Vegetable.Asparagus;
Open in Playgroundenum Fruit {
Apple,
}
declare let fruit: Fruit;
fruit === Fruit.Apple;
enum Vegetable {
Asparagus = 'asparagus',
}
declare let vegetable: Vegetable;
vegetable === Vegetable.Asparagus;
Open in Playground