typescript/no-mixed-enums Pedantic
作用
此规则不允许枚举同时包含字符串成员和数字成员。
为什么这不好?
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,
}如何使用
To enable this rule using the config file or in the CLI, you can use:
json
{
"options": {
"typeAware": true
},
"rules": {
"typescript/no-mixed-enums": "error"
}
}ts
import { defineConfig } from "oxlint";
export default defineConfig({
options: { typeAware: true },
rules: {
"typescript/no-mixed-enums": "error",
},
});bash
oxlint --type-aware --deny typescript/no-mixed-enums版本
此规则已在 v1.12.0 中添加。
