Skip to content

useLiteralEnumMembers

诊断类别:lint/style/useLiteralEnumMembers

¥Diagnostic Category: lint/style/useLiteralEnumMembers

自从:v1.0.0

¥Since: v1.0.0

来源:

¥Sources:

要求所有枚举成员都是文字值。

¥Require all enum members to be literal values.

通常,枚举成员用文字数字或文字字符串初始化。但是,TypeScript 允许枚举成员的值是多种不同类型的表达式。使用计算枚举成员通常容易出错且令人困惑。此规则要求使用常量表达式初始化枚举成员。它允许使用数字和按位表达式来支持 枚举标志。它还允许引用以前的枚举成员。

¥Usually, an enum member is initialized with a literal number or a literal string. However, TypeScript allows the value of an enum member to be many different kinds of expressions. Using a computed enum member is often error-prone and confusing. This rule requires the initialization of enum members with constant expressions. It allows numeric and bitwise expressions for supporting enum flags. It also allows referencing previous enum members.

¥Examples

¥Invalid

const x = 2;
enum Computed {
A,
B = x,
}
code-block.ts:4:9 lint/style/useLiteralEnumMembers ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

The enum member should be initialized with a literal value such as a number or a string.

2 │ enum Computed {
3 │ A,
> 4 │ B = x,
^
5 │ }
6 │

¥Valid

enum Direction {
Left,
Right,
}
enum Order {
Less = -1,
Equal = 0,
Greater = 1,
}
enum State {
Open = "Open",
Close = "Close",
}
enum FileAccess {
None = 0,
Read = 1,
Write = 1 << 1,
All = Read | Write
}

¥Related links