Skip to main content

prefer-literal-enum-member

要求所有枚举成员均为字面量值.

🔒

ESLint 配置 中扩展"plugin:@typescript-eslint/strict" 可启用此规则。

TypeScript 允许枚举成员的值是多种不同类型的有效 JavaScript 表达式。然而,由于枚举创建了自己的作用域,其中每个枚举成员都成为该作用域中的变量,因此开发者常常对结果值感到惊讶。例如:

¥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?
}

答案是 Foo.c 在运行时将是 1 [TypeScript 在线运行]。

¥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.

eslint.config.mjs
export default tseslint.config({
rules: {
"@typescript-eslint/prefer-literal-enum-member": "error"
}
});

在线运行试试这个规则 ↗

示例

¥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

选项

该规则接受以下选项:

type Options = [
{
/** 是否允许在枚举初始化器中使用按位表达式。 */
allowBitwiseExpressions?: boolean;
},
];

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

¥Options

allowBitwiseExpressions

是否允许在枚举初始化器中使用按位表达式。 Default: false.

{ "allowBitwiseExpressions": true } 选项的代码示例:

¥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.

资源