typescript/no-unsafe-enum-comparison 可疑
它做了什么
此规则禁止将枚举值与非枚举值进行比较。
为什么这是不好的?
枚举值应仅以类型安全的方式与其他同类型枚举值或其底层字面量值进行比较。将枚举与无关的值进行比较可能导致意外行为,并违背了使用枚举实现类型安全的初衷。
示例
此规则的错误代码示例:
ts
enum Status {
Open = "open",
Closed = "closed",
}
enum Color {
Red = "red",
Blue = "blue",
}
declare const status: Status;
declare const color: Color;
declare const str: string;
// 将不同枚举进行比较
if (status === color) {
} // 不安全
// 将枚举与字符串比较(除非是匹配的字面量)
if (status === str) {
} // 不安全
// 与任意值比较
if (status === "unknown") {
} // 不安全此规则的正确代码示例:
ts
enum Status {
Open = "open",
Closed = "closed",
}
declare const status: Status;
// 与相同枚举值进行比较
if (status === Status.Open) {
} // 安全
// 与正确的字面量类型进行比较
if (status === "open") {
} // 安全
// 使用枚举方法
if (Object.values(Status).includes(someValue)) {
} // 检查的推荐方式如何使用
要通过配置文件或 CLI 启用此规则,可以使用:
json
{
"rules": {
"typescript/no-unsafe-enum-comparison": "error"
}
}bash
oxlint --type-aware --deny typescript/no-unsafe-enum-comparison