@typescript-eslint/no-unsafe-enum-comparison
Disallow comparing an enum value with a plain number or string
has suggestionsneeds types
Also called typescript-eslint/no-unsafe-enum-comparison, typescript/no-unsafe-enum-comparison
Comparing an enum with a raw value, as in status === 1, ties the code to the number behind the member. If you reorder the enum or insert a member, the comparison means something else and you get no compile error.
The rule checks ==, !=, ===, !==, <, <=, >, >= and the case labels of a switch. Comparing members of two different enums is reported too.
bun lint --type-aware turns this rule on in TypeScript files.
Configure#
Off by default. This rule needs types, so turning it on makes bun lint type check your code first.
bunfig.toml
[lint.rules]
"@typescript-eslint/no-unsafe-enum-comparison" = "error" # or "warn"Examples#
example.ts3 problems
enum Status {
Open,
Closed,
}
enum Color {
Red = "red",
}
function describe(status: Status, color: Color) {
if (status === 1The two values in this comparison do not have a shared enum type.) {
return "closed";
}
if (color === "red"The two values in this comparison do not have a shared enum type.) {
return "red";
}
switch (status) {
case 0:The case statement does not have a shared enum type with the switch predicate.
return "open";
}
}example.tsNo problems
enum Status {
Open,
Closed,
}
enum Color {
Red = "red",
}
function describe(status: Status, color: Color) {
if (status === Status.Closed) {
return "closed";
}
if (color === Color.Red) {
return "red";
}
switch (status) {
case Status.Open:
return "open";
}
}A comparison with another kind of value, such as undefined, isn't reported:
example.tsNo problems
enum Status {
Open,
Closed,
}
function isSet(status?: Status) {
return status !== undefined;
}