typescript/strict-boolean-expressions Pedantic
功能说明
禁止布尔表达式中的某些类型。
为什么这样做是不好的?
禁止在期望布尔值的表达式中使用非布尔类型。始终允许 boolean 和 never 类型。可以通过选项配置在布尔上下文中被认为安全的其他类型。
检查以下节点:
!、&&和||运算符的参数- 条件表达式中的条件(
cond ? x : y) if、for、while和do-while语句的条件。
示例
此规则的错误代码示例:
ts
const str = "hello";
if (str) {
console.log("string");
}
const num = 42;
if (num) {
console.log("number");
}
const obj = { foo: "bar" };
if (obj) {
console.log("object");
}
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("string");
}
const num = 42;
if (num !== 0) {
console.log("number");
}
const obj = { foo: "bar" };
if (obj !== null) {
console.log("object");
}
declare const maybeString: string | undefined;
if (maybeString !== undefined) {
console.log(maybeString);
}
const bool = true;
if (bool) {
console.log("boolean");
}配置
此规则接受具有以下属性的配置对象:
allowAny
类型:boolean
默认值:false
是否允许布尔上下文中的 any 类型。
allowNullableBoolean
类型:boolean
默认值:false
是否允许布尔上下文中的可空布尔类型(例如 boolean | null)。
allowNullableEnum
类型:boolean
默认值:false
是否允许布尔上下文中的可空枚举类型。
allowNullableNumber
类型:boolean
默认值:false
是否允许布尔上下文中的可空数字类型(例如 number | null)。
allowNullableObject
类型:boolean
默认值:true
是否允许布尔上下文中的可空对象类型。
allowNullableString
类型:boolean
默认值:false
是否允许布尔上下文中的可空字符串类型(例如 string | null)。
allowNumber
类型:boolean
默认值:true
是否允许布尔上下文中的数字类型(检查非零数字)。
allowString
类型:boolean
默认值:true
是否允许布尔上下文中的字符串类型(检查非空字符串)。
如何使用
To enable this rule using the config file or in the CLI, you can use:
json
{
"options": {
"typeAware": true
},
"rules": {
"typescript/strict-boolean-expressions": "error"
}
}ts
import { defineConfig } from "oxlint";
export default defineConfig({
options: { typeAware: true },
rules: {
"typescript/strict-boolean-expressions": "error",
},
});bash
oxlint --type-aware --deny typescript/strict-boolean-expressions版本
此规则添加于 v1.25.0。