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.
💡
Some problems reported by this rule are manually fixable by editor suggestions.
💭
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;
Open in Playgroundenum Vegetable {
Asparagus = 'asparagus',
}
declare let vegetable: Vegetable;
vegetable === 'asparagus';
Open in Playgroundenum Fruit {
Apple,
}
declare let fruit: Fruit;
fruit === Fruit.Banana;
Open in Playgroundenum Vegetable {
Asparagus = 'asparagus',
}
declare let vegetable: Vegetable;
vegetable === Vegetable.Asparagus;
Open in PlaygroundOptions
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.