typescript/strict-boolean-expressions 严谨
它的作用
禁止在布尔表达式中使用某些类型。
为什么这是不好的?
禁止在期望为布尔值的表达式中使用非布尔类型。boolean 和 never 类型始终被允许。可以通过选项配置其他在布尔上下文中被认为是安全的类型。
以下节点会被检查:
!、&&和||操作符的参数- 条件表达式中的条件(
cond ? x : y) if、for、while和do-while语句的条件
示例
此规则的错误代码示例:
ts
const str = "hello";
if (str) {
console.log("字符串");
}
const num = 42;
if (num) {
console.log("数字");
}
const obj = { foo: "bar" };
if (obj) {
console.log("对象");
}
declare const maybeString: string | undefined;
if (maybeString) {
console.log(maybeString);
}
const result = str && num;
const ternary = str ? "yes" : "no";此规则的正确代码示例:
ts
const str = "hello";
if (str !== "") {
console.log("字符串");
}
const num = 42;
if (num !== 0) {
console.log("数字");
}
const obj = { foo: "bar" };
if (obj !== null) {
console.log("对象");
}
declare const maybeString: string | undefined;
if (maybeString !== undefined) {
console.log(maybeString);
}
const bool = true;
if (bool) {
console.log("布尔值");
}配置
此规则接受一个配置对象,包含以下属性:
allowAny
type: boolean
default: false
是否允许在布尔上下文中使用 any 类型。
allowNullableBoolean
type: boolean
default: false
是否允许在布尔上下文中使用可空布尔类型(例如 boolean | null)。
allowNullableEnum
type: boolean
default: false
是否允许在布尔上下文中使用可空枚举类型。
allowNullableNumber
type: boolean
default: false
是否允许在布尔上下文中使用可空数字类型(例如 number | null)。
allowNullableObject
type: boolean
default: true
是否允许在布尔上下文中使用可空对象类型。
allowNullableString
type: boolean
default: false
是否允许在布尔上下文中使用可空字符串类型(例如 string | null)。
allowNumber
type: boolean
default: true
是否允许在布尔上下文中使用数字类型(检查非零数字)。
allowString
type: boolean
default: true
是否允许在布尔上下文中使用字符串类型(检查非空字符串)。
如何使用
要通过配置文件或 CLI 启用此规则,可以使用:
json
{
"rules": {
"typescript/strict-boolean-expressions": "error"
}
}bash
oxlint --type-aware --deny typescript/strict-boolean-expressions