typescript/no-mixed-enums 严谨
它的作用
此规则禁止枚举同时包含字符串成员和数字成员。
为什么这是个问题?
TypeScript 枚举可以具有字符串、数字或计算值成员。在同一枚举中混合使用字符串和数字成员可能导致混淆,并由于 TypeScript 编译枚举的方式而引发意外的运行时行为。
示例
以下为错误用法示例:
ts
enum Status {
Open = 1,
Closed = "closed",
}
enum Direction {
Up = "up",
Down = 2,
Left = "left",
Right = 4,
}以下为正确用法示例:
ts
// 全为数字
enum Status {
Open = 1,
Closed = 2,
}
// 全为字符串
enum Direction {
Up = "up",
Down = "down",
Left = "left",
Right = "right",
}
// 自动递增的数字
enum Color {
Red,
Green,
Blue,
}如何使用
要通过配置文件或 CLI 启用此规则,可以使用:
json
{
"rules": {
"typescript/no-mixed-enums": "error"
}
}bash
oxlint --type-aware --deny typescript/no-mixed-enums