Skip to main content

prefer-literal-enum-member

Require all enum members to be literal values.

🔒

Extending "plugin:@typescript-eslint/strict" in an ESLint configuration enables this rule.

TypeScript allows the value of an enum member to be many different kinds of valid JavaScript expressions. However, because enums create their own scope whereby each enum member becomes a variable in that scope, developers are often surprised at the resultant values. For example:

const imOutside = 2;
const b = 2;
enum Foo {
outer = imOutside,
a = 1,
b = a,
c = b,
// does c == Foo.b == Foo.c == 1?
// or does c == b == 2?
}

The answer is that Foo.c will be 1 at runtime [TypeScript playground].

Therefore, it's often better to prevent unexpected results in code by requiring the use of literal values as enum members. This rule reports when an enum member is given a value that is not a literal.

.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/prefer-literal-enum-member": "error"
}
};

Try this rule in the playground ↗

Examples

const str = 'Test';
const string1 = 'string1';
const string2 = 'string2';

enum Invalid {
A = str, // Variable assignment
B = `Interpolates ${string1} and ${string2}`, // Template literal with interpolation
C = 2 + 2, // Expression assignment
D = C, // Assignment to another enum member
}
Open in Playground

Options

This rule accepts the following options:

type Options = [
{
/** Whether to allow using bitwise expressions in enum initializers. */
allowBitwiseExpressions?: boolean;
},
];

const defaultOptions: Options = [{ allowBitwiseExpressions: false }];

allowBitwiseExpressions

Whether to allow using bitwise expressions in enum initializers (default: false).

Examples of code for the { "allowBitwiseExpressions": true } option:

const x = 1;
enum Foo {
A = x << 0,
B = x >> 0,
C = x >>> 0,
D = x | 0,
E = x & 0,
F = x ^ 0,
G = ~x,
}
Open in Playground

When Not To Use It

If you want use anything other than simple literals as an enum value, this rule might not be for you.

Resources