Skip to content

useEnumInitializers

诊断类别:lint/style/useEnumInitializers

¥Diagnostic Category: lint/style/useEnumInitializers

自从:v1.0.0

¥Since: v1.0.0

来源:

¥Sources:

要求每个枚举成员值都明确初始化。

¥Require that each enum member value be explicitly initialized.

TypeScript 枚举是一种组织语义相关常量值的实用方法。没有明确值的枚举成员默认被赋予连续增加的数字。

¥TypeScript enums are a practical way to organize semantically related constant values. Members of enums that don’t have explicit values are by default given sequentially increasing numbers.

当枚举成员的值很重要时,如果枚举声明随着时间的推移而修改,允许枚举成员的隐式值可能会导致错误。

¥When the value of enum members are important, allowing implicit values for enum members can cause bugs if enum declarations are modified over time.

¥Examples

¥Invalid

enum Version {
V1,
}
code-block.ts:1:6 lint/style/useEnumInitializers  FIXABLE  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

This enum declaration contains members that are implicitly initialized.

> 1 │ enum Version {
^^^^^^^
2 │ V1,
3 │ }

This enum member should be explicitly initialized.

1 │ enum Version {
> 2 │ V1,
^^
3 │ }
4 │

Allowing implicit initializations for enum members can cause bugs if enum declarations are modified over time.

Safe fix: Initialize all enum members.

2 │ ····V1·=·0,
++++
enum Status {
Open = 1,
Close,
}
code-block.ts:1:6 lint/style/useEnumInitializers  FIXABLE  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

This enum declaration contains members that are implicitly initialized.

> 1 │ enum Status {
^^^^^^
2 │ Open = 1,
3 │ Close,

This enum member should be explicitly initialized.

1 │ enum Status {
2 │ Open = 1,
> 3 │ Close,
^^^^^
4 │ }
5 │

Allowing implicit initializations for enum members can cause bugs if enum declarations are modified over time.

Safe fix: Initialize all enum members.

3 │ ····Close·=·2,
++++
enum Color {
Red = "Red",
Green = "Green",
Blue,
}
code-block.ts:1:6 lint/style/useEnumInitializers  FIXABLE  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

This enum declaration contains members that are implicitly initialized.

> 1 │ enum Color {
^^^^^
2 │ Red = “Red”,
3 │ Green = “Green”,

This enum member should be explicitly initialized.

2 │ Red = “Red”,
3 │ Green = “Green”,
> 4 │ Blue,
^^^^
5 │ }
6 │

Allowing implicit initializations for enum members can cause bugs if enum declarations are modified over time.

Safe fix: Initialize all enum members.

4 │ ····Blue·=·Blue,
+++++++++

¥Valid

enum Status {
Open = 1,
Close = 2,
}
enum Color {
Red = "Red",
Green = "Green",
Blue = "Blue",
}
declare enum Weather {
Rainy,
Sunny,
}

¥Related links