strict-boolean-expressions
Disallow certain types in boolean expressions.
禁止在需要布尔值的表达式中使用非布尔类型。
始终允许 boolean
和 never
类型。
在布尔上下文中被认为安全的其他类型可以通过选项进行配置。
英:Forbids usage of non-boolean types in expressions where a boolean is expected.
boolean
and never
types are always allowed.
Additional types which are considered safe in a boolean context can be configured via options.
以下节点被视为布尔表达式并检查其类型:
英:The following nodes are considered boolean expressions and their type is checked:
- 逻辑非运算符 (
!arg
) 的参数。 - 条件表达式(
cond ? x : y
)中的条件。 if
、for
、while
和do-while
语句的条件。- 逻辑二元运算符(
lhs || rhs
和lhs && rhs
)的操作数。- 当右侧操作数不是另一个布尔表达式的后代时,它会被忽略。 这是为了允许使用布尔运算符来实现其短路行为。
module.exports = {
"rules": {
"@typescript-eslint/strict-boolean-expressions": "error"
}
};
示例
- ❌ 不正确
- ✅ 正确
// nullable numbers are considered unsafe by default
let num: number | undefined = 0;
if (num) {
console.log('num is defined');
}
// nullable strings are considered unsafe by default
let str: string | null = null;
if (!str) {
console.log('str is empty');
}
// nullable booleans are considered unsafe by default
function foo(bool?: boolean) {
if (bool) {
bar();
}
}
// `any`, unconstrained generics and unions of more than one primitive type are disallowed
const foo = <T>(arg: T) => (arg ? 1 : 0);
// always-truthy and always-falsy types are disallowed
let obj = {};
while (obj) {
obj = getObj();
}
Open in Playground// Using logical operator short-circuiting is allowed
const Component = () => {
const entry = map.get('foo') || {};
return entry && <p>Name: {entry.name}</p>;
};
// nullable values should be checked explicitly against null or undefined
let num: number | undefined = 0;
if (num != null) {
console.log('num is defined');
}
let str: string | null = null;
if (str != null && !str) {
console.log('str is empty');
}
function foo(bool?: boolean) {
if (bool ?? false) {
bar();
}
}
// `any` types should be cast to boolean explicitly
const foo = (arg: any) => (Boolean(arg) ? 1 : 0);
Open in Playground选项
allowString
允许布尔上下文中的 string
。
这是安全的,因为字符串只有一个假值 (""
)。
如果你喜欢显式 str != ""
或 str.length > 0
样式,请将其设置为 false
。
英:Allows string
in a boolean context.
This is safe because strings have only one falsy value (""
).
Set this to false
if you prefer the explicit str != ""
or str.length > 0
style.
allowNumber
允许布尔上下文中的 number
。
这是安全的,因为数字只有两个假值(0
和 NaN
)。
如果你喜欢显式的 num != 0
和 !Number.isNaN(num)
样式,请将其设置为 false
。
英:Allows number
in a boolean context.
This is safe because numbers have only two falsy values (0
and NaN
).
Set this to false
if you prefer the explicit num != 0
and !Number.isNaN(num)
style.
allowNullableObject
允许布尔上下文中的 object | function | symbol | null | undefined
。
这是安全的,因为对象、函数和符号没有假值。
如果你喜欢显式 obj != null
样式,请将其设置为 false
。
英:Allows object | function | symbol | null | undefined
in a boolean context.
This is safe because objects, functions and symbols don't have falsy values.
Set this to false
if you prefer the explicit obj != null
style.
allowNullableBoolean
允许布尔上下文中的 boolean | null | undefined
。
这是不安全的,因为可为 null 的布尔值可以是 false
或 nullish。
如果你想强制执行显式 bool ?? false
或 bool ?? true
样式,请将其设置为 false
。
如果你不介意隐式将 false 视为空值,请将其设置为 true
。
英:Allows boolean | null | undefined
in a boolean context.
This is unsafe because nullable booleans can be either false
or nullish.
Set this to false
if you want to enforce explicit bool ?? false
or bool ?? true
style.
Set this to true
if you don't mind implicitly treating false the same as a nullish value.
allowNullableString
允许布尔上下文中的 string | null | undefined
。
这是不安全的,因为可为 null 的字符串可以是空字符串或 nullish。
如果你不介意将空字符串隐式地视为空值,请将其设置为 true
。
英:Allows string | null | undefined
in a boolean context.
This is unsafe because nullable strings can be either an empty string or nullish.
Set this to true
if you don't mind implicitly treating an empty string the same as a nullish value.
allowNullableNumber
允许布尔上下文中的 number | null | undefined
。
这是不安全的,因为可为空的数字可以是虚假数字或无效数字。
如果你不介意隐式将零或 NaN 视为空值,请将其设置为 true
。
英:Allows number | null | undefined
in a boolean context.
This is unsafe because nullable numbers can be either a falsy number or nullish.
Set this to true
if you don't mind implicitly treating zero or NaN the same as a nullish value.
allowNullableEnum
允许布尔上下文中的 enum | null | undefined
。
这是不安全的,因为可为 null 的枚举可以是假数或 nullish。
如果你不介意将值为零的枚举隐式地视为空值,请将其设置为 true
。
英:Allows enum | null | undefined
in a boolean context.
This is unsafe because nullable enums can be either a falsy number or nullish.
Set this to true
if you don't mind implicitly treating an enum whose value is zero the same as a nullish value.
allowAny
允许布尔上下文中的 any
。
由于显而易见的原因,这是不安全的。
将其设置为 true
的风险由你自行承担。
英:Allows any
in a boolean context.
This is unsafe for obvious reasons.
Set this to true
at your own risk.
allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing
如果将其设置为 false
,则该规则将在 tsconfig.json
未将 strictNullChecks
编译器选项(或 strict
)设置为 true
的每个文件上出错。
英:If this is set to false
, then the rule will error on every file whose tsconfig.json
does not have the strictNullChecks
compiler option (or strict
) set to true
.
如果没有 strictNullChecks
,TypeScript 本质上会从类型中删除 undefined
和 null
。 这意味着当此规则检查变量 它无法判断该变量可能是 null
或 undefined
的类型时,这实际上使此规则的用处大大降低。
英:Without strictNullChecks
, TypeScript essentially erases undefined
and null
from the types. This means when this rule inspects the types from a variable, it will not be able to tell that the variable might be null
or undefined
, which essentially makes this rule a lot less useful.
你应该使用 strictNullChecks
来确保代码库中的完全类型安全。
英:You should be using strictNullChecks
to ensure complete type-safety in your codebase.
如果由于某种原因你无法打开 strictNullChecks
,但仍想使用此规则 - 你可以使用此选项来允许它 - 但要知道,在编译器选项关闭的情况下,此规则的行为是未定义的。 如果你使用此选项,我们将不接受错误报告。
英:If for some reason you cannot turn on strictNullChecks
, but still want to use this rule - you can use this option to allow it - but know that the behavior of this rule is undefined with the compiler option turned off. We will not accept bug reports if you are using this option.
修复和建议
此规则为布尔上下文中的特定类型提供以下修复和建议:
英:This rule provides following fixes and suggestions for particular types in boolean context:
boolean
- 始终允许 - 无需修复。string
- (当allowString
为false
时) - 提供以下建议:- 更改条件以检查字符串的长度 (
str
→str.length > 0
) - 更改条件以检查空字符串 (
str
→str !== ""
) - 将值显式转换为布尔值 (
str
→Boolean(str)
)
- 更改条件以检查字符串的长度 (
number
- (当allowNumber
为false
时):- 对于
array.length
- 提供 autofix:- 更改条件以检查 0 (
array.length
→array.length > 0
)
- 更改条件以检查 0 (
- 对于其他数值 - 提供以下建议:
- 更改条件以检查 0 (
num
→num !== 0
) - 更改条件以检查 NaN (
num
→!Number.isNaN(num)
) - 将值显式转换为布尔值 (
num
→Boolean(num)
)
- 更改条件以检查 0 (
- 对于
object | null | undefined
- (当allowNullableObject
为false
时) - 提供 autofix:- 更改条件以检查 null/未定义 (
maybeObj
→maybeObj != null
)
- 更改条件以检查 null/未定义 (
boolean | null | undefined
- 提供以下建议:- 明确将 null 值视为 false (
maybeBool
→maybeBool ?? false
) - 更改条件以检查真/假 (
maybeBool
→maybeBool === true
)
- 明确将 null 值视为 false (
string | null | undefined
- 提供以下建议:- 更改条件以检查 null/未定义 (
maybeStr
→maybeStr != null
) - 明确将 null 值视为空字符串 (
maybeStr
→maybeStr ?? ""
) - 将值显式转换为布尔值 (
maybeStr
→Boolean(maybeStr)
)
- 更改条件以检查 null/未定义 (
number | null | undefined
- 提供以下建议:- 更改条件以检查 null/未定义 (
maybeNum
→maybeNum != null
) - 明确将空值视为 0 (
maybeNum
→maybeNum ?? 0
) - 将值显式转换为布尔值 (
maybeNum
→Boolean(maybeNum)
)
- 更改条件以检查 null/未定义 (
any
andunknown
- 提供以下建议:- 将值显式转换为布尔值 (
value
→Boolean(value)
)
- 将值显式转换为布尔值 (
何时不使用它
如果你的项目不太可能遇到逻辑条件中使用的虚假非布尔值导致的错误,则可以跳过启用此规则。
英:If your project isn't likely to experience bugs from falsy non-boolean values being used in logical conditions, you can skip enabling this rule.
否则,该规则对于逻辑检查中要求精确比较的要求可能非常严格。 如果你更喜欢更简洁的检查而不是更精确的布尔逻辑,则此规则可能不适合你。
英:Otherwise, this rule can be quite strict around requiring exact comparisons in logical checks. If you prefer more succinct checks over more precise boolean logic, this rule might not be for you.
相关
- no-unnecessary-condition - 类似的规则,报告条件中始终为真和始终为假的值
选项
该规则接受以下选项
type Options = [
{
allowAny?: boolean;
allowNullableBoolean?: boolean;
allowNullableEnum?: boolean;
allowNullableNumber?: boolean;
allowNullableObject?: boolean;
allowNullableString?: boolean;
allowNumber?: boolean;
allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing?: boolean;
allowString?: boolean;
},
];
const defaultOptions: Options = [
{
allowString: true,
allowNumber: true,
allowNullableObject: true,
allowNullableBoolean: false,
allowNullableString: false,
allowNullableNumber: false,
allowNullableEnum: false,
allowAny: false,
allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing: false,
},
];