no-unsafe-enum-comparison
Disallow comparing an enum value with a non-enum value.
✅
Extending "plugin:@typescript-eslint/recommended-type-checked"
in an ESLint configuration enables this rule.
💭
This rule requires type information to run.
The TypeScript compiler can be surprisingly lenient when working with enums. For example, it will allow you to compare enum values against numbers even though they might not have any type overlap:
enum Fruit {
Apple,
Banana,
}
declare let fruit: Fruit;
fruit === 999; // No error
This rule flags when an enum typed value is compared to a non-enum number
.
.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/no-unsafe-enum-comparison": "error"
}
};
Examples
- ❌ Incorrect
- ✅ Correct
enum Fruit {
Apple,
}
declare let fruit: Fruit;
fruit === 999;
enum Vegetable {
Asparagus = 'asparagus',
}
declare let vegetable: Vegetable;
vegetable === 'asparagus';
enum Fruit {
Apple,
}
declare let fruit: Fruit;
fruit === Fruit.Banana;
enum Vegetable {
Asparagus = 'asparagus',
}
declare let vegetable: Vegetable;
vegetable === Vegetable.Asparagus;
Options
This rule is not configurable.
When Not To Use It
If you don't mind number and/or literal string constants being compared against enums, you likely don't need this rule.