@typescript-eslint/prefer-literal-enum-member
Require enum values to be literals, not computed expressions
Also called typescript-eslint/prefer-literal-enum-member, typescript/prefer-literal-enum-member
An enum value can be any expression, but then you need to evaluate it in your head to know what the member is. Names can also surprise you. Inside an enum, a name refers to another member before it refers to a variable outside, so Max = limit reads the member limit if there is one, not the const limit above the enum.
Strings, numbers, a - or + in front of a number, and template strings without ${} are allowed. A member without a value isn't checked.
Configure#
Off by default. To turn it on:
[lint.rules]
"@typescript-eslint/prefer-literal-enum-member" = "error" # or "warn"Every option, set to its default:
[lint.rules]
"@typescript-eslint/prefer-literal-enum-member" = ["error", {
allowBitwiseExpressions = false,
}]Examples#
const prefix = "app";
enum Key {
SessionExplicit enum value must only be a literal value (string or number). = `${prefix}:session`,
LengthExplicit enum value must only be a literal value (string or number). = "session".length,
TotalExplicit enum value must only be a literal value (string or number). = 1 + 2,
}enum Key {
Session = "app:session",
Length = 7,
Offset = -1,
Next,
}Options#
| Option | Default | What it does |
|---|---|---|
allowBitwiseExpressions | false | Allow |, &, ^, ~, <<, >>, and >>> on literals and on other members of the same enum. |
Flags are often written with shifts. Without the option, each of these is reported:
enum Permission {
ReadExplicit enum value must only be a literal value (string or number). = 1 << 0,
WriteExplicit enum value must only be a literal value (string or number). = 1 << 1,
AllExplicit enum value must only be a literal value (string or number). = Read | Write,
}With allowBitwiseExpressions: true, none of them are reported:
{ "allowBitwiseExpressions": true }No problemsenum Permission {
Read = 1 << 0,
Write = 1 << 1,
All = Read | Write,
}A variable from outside the enum is still reported:
{ "allowBitwiseExpressions": true }1 problemconst base = 8;
enum Permission {
AdminExplicit enum value must only be a literal value (string or number) or a bitwise expression. = base | 1,
}