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)) {
} // 一种安全的检查方式如何使用
To enable this rule using the config file or in the CLI, you can use:
json
{
"options": {
"typeAware": true
},
"rules": {
"typescript/no-unsafe-enum-comparison": "error"
}
}ts
import { defineConfig } from "oxlint";
export default defineConfig({
options: { typeAware: true },
rules: {
"typescript/no-unsafe-enum-comparison": "error",
},
});bash
oxlint --type-aware --deny typescript/no-unsafe-enum-comparison版本
此规则是在 v1.12.0 中添加的。
