Skip to main content

no-mixed-enums

禁止枚举同时具有数字和字符串成员.

🔒

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

💭

该规则需要 类型信息 才能运行,但这会带来性能方面的权衡。

TypeScript 枚举可以为其成员分配数字或字符串值。大多数枚举包含所有数字或所有字符串,但理论上你可以在同一枚举中混合搭配。混合枚举成员类型通常被认为是令人困惑且不好的做法。

¥TypeScript enums are allowed to assign numeric or string values to their members. Most enums contain either all numbers or all strings, but in theory you can mix-and-match within the same enum. Mixing enum member types is generally considered confusing and a bad practice.

eslint.config.mjs
export default tseslint.config({
rules: {
"@typescript-eslint/no-mixed-enums": "error"
}
});

在线运行试试这个规则 ↗

示例

¥Examples

enum Status {
Unknown,
Closed = 1,
Open = 'open',
}
Open in Playground

混合枚举成员值的迭代陷阱

¥Iteration Pitfalls of Mixed Enum Member Values

可以使用 Object.entries/Object.keys/Object.values 迭代枚举值。

¥Enum values may be iterated over using Object.entries/Object.keys/Object.values.

如果所有枚举成员都是字符串,则项目数将与枚举成员数匹配:

¥If all enum members are strings, the number of items will match the number of enum members:

enum Status {
Closed = 'closed',
Open = 'open',
}

// ['closed', 'open']
Object.values(Status);

但是,如果枚举包含用数字初始化的成员(包括隐式初始化的数字),则对该枚举的迭代也将包括这些数字:

¥But if the enum contains members that are initialized with numbers -including implicitly initialized numbers— then iteration over that enum will include those numbers as well:

enum Status {
Unknown,
Closed = 1,
Open = 'open',
}

// ["Unknown", "Closed", 0, 1, "open"]
Object.values(Status);

选项

该规则不可配置。

何时不使用它

¥When Not To Use It

如果你不介意混合枚举成员值的混乱并且不迭代枚举,则可以安全地禁用此规则。

¥If you don't mind the confusion of mixed enum member values and don't iterate over enums, you can safely disable this rule.


Type checked lint rules are more powerful than traditional lint rules, but also require configuring type checked linting.

See Troubleshooting > Linting with Type Information > Performance if you experience performance degradations after enabling type checked rules.

资源