Skip to main content

strict-boolean-expressions

Disallow certain types in boolean expressions.

💡

此规则报告的一些问题可以通过编辑器 建议 手动修复。

💭

该规则需要 类型信息 才能运行,但这会带来性能方面的权衡。

禁止在需要布尔值的表达式中使用非布尔类型。booleannever 类型始终是允许的。在布尔上下文中被认为安全的其他类型可以通过选项进行配置。

¥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)的参数。

    ¥Argument to the logical negation operator (!arg).

  • 条件表达式中的条件(cond ? x : y)。

    ¥The condition in a conditional expression (cond ? x : y).

  • ifforwhiledo-while 语句的条件。

    ¥Conditions for if, for, while, and do-while statements.

  • 逻辑二元运算符的操作数(lhs || rhslhs && rhs)。

    ¥Operands of logical binary operators (lhs || rhs and lhs && rhs).

    • 当右侧操作数不是另一个布尔表达式的后代时,它会被忽略。这是为了允许使用布尔运算符来实现其短路行为。

      ¥Right-hand side operand is ignored when it's not a descendant of another boolean expression. This is to allow usage of boolean operators for their short-circuiting behavior.

  • 断言函数 (assert(arg)) 的断言参数。

    ¥Asserted argument of an assertion function (assert(arg)).

  • 返回数组谓词函数的类型,例如 filter()some() 等。

    ¥Return type of array predicate functions such as filter(), some(), etc.

eslint.config.mjs
export default tseslint.config({
rules: {
"@typescript-eslint/strict-boolean-expressions": "error"
}
});

在线运行试试这个规则 ↗

示例

¥Examples

// nullable numbers are considered unsafe by default
declare const num: number | undefined;
if (num) {
console.log('num is defined');
}

// nullable strings are considered unsafe by default
declare const str: string | 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();
}

// assertion functions without an `is` are boolean contexts.
declare function assert(value: unknown): asserts value;
let maybeString = Math.random() > 0.5 ? '' : undefined;
assert(maybeString);

// array predicates' return types are boolean contexts.
['one', null].filter(x => x);
Open in Playground

选项

该规则接受以下选项:

type Options = [
{
/** Whether to allow `any`s in a boolean context. */
allowAny?: boolean;
/** Whether to allow nullable `boolean`s in a boolean context. */
allowNullableBoolean?: boolean;
/** Whether to allow nullable `enum`s in a boolean context. */
allowNullableEnum?: boolean;
/** Whether to allow nullable `number`s in a boolean context. */
allowNullableNumber?: boolean;
/** Whether to allow nullable `object`s, `symbol`s, and functions in a boolean context. */
allowNullableObject?: boolean;
/** Whether to allow nullable `string`s in a boolean context. */
allowNullableString?: boolean;
/** Whether to allow `number`s in a boolean context. */
allowNumber?: boolean;
/** Unless this is set to `true`, the rule will error on every file whose `tsconfig.json` does _not_ have the `strictNullChecks` compiler option (or `strict`) set to `true`. */
allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing?: boolean;
/** Whether to allow `string`s in a boolean context. */
allowString?: boolean;
},
];

const defaultOptions: Options = [
{
allowAny: false,
allowNullableBoolean: false,
allowNullableEnum: false,
allowNullableNumber: false,
allowNullableObject: true,
allowNullableString: false,
allowNumber: true,
allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing: false,
allowString: true,
},
];

¥Options

allowString

Whether to allow strings in a boolean context. Default: true.

这可能是安全的,因为字符串只有一个假值("")。如果你更喜欢显式 str != ""str.length > 0 样式,请将其设置为 false

¥This can be safe because strings have only one falsy value (""). Set this to false if you prefer the explicit str != "" or str.length > 0 style.

allowNumber

Whether to allow numbers in a boolean context. Default: true.

这可能是安全的,因为数字只有两个假值(0NaN)。如果你更喜欢显式 num != 0!Number.isNaN(num) 样式,请将其设置为 false

¥This can be 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

Whether to allow nullable objects, symbols, and functions in a boolean context. Default: true.

这可能是安全的,因为对象、函数和符号没有假值。如果你更喜欢显式 obj != null 样式,请将其设置为 false

¥This can be safe because objects, functions, and symbols don't have falsy values. Set this to false if you prefer the explicit obj != null style.

allowNullableBoolean

Whether to allow nullable booleans in a boolean context. Default: false.

这是不安全的,因为可空布尔值可以是 false 或 nullish。如果你想强制执行显式 bool ?? falsebool ?? true 样式,请将其设置为 false。如果你不介意将 false 隐式地视为与空值相同,请将其设置为 true

¥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

Whether to allow nullable strings in a boolean context. Default: false.

这是不安全的,因为可为 null 的字符串可以是空字符串或 nullish。如果你不介意将空字符串隐式地视为与空值相同,请将其设置为 true

¥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

Whether to allow nullable numbers in a boolean context. Default: false.

这是不安全的,因为可为空的数字可以是虚假数字或无效数字。如果你不介意将零或 NaN 隐式地视为与空值相同,请将其设置为 true

¥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

Whether to allow nullable enums in a boolean context. Default: false.

这是不安全的,因为可为 null 的枚举可以是假数或 nullish。如果你不介意将值为零的枚举隐式地视为与空值相同,请将其设置为 true

¥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

Whether to allow anys in a boolean context. Default: false.

这是不安全的,因为 any 允许任何值并禁用许多类型检查。请自行承担风险,将其设置为 true

¥This is unsafe for because any allows any values and disables many type checking checks. Set this to true at your own risk.

allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing

Unless this is set to true, the rule will error on every file whose tsconfig.json does not have the strictNullChecks compiler option (or strict) set to true. Default: false.

已弃用

此选项将在下一个主要版本的 typescript-eslint 中删除。

¥This option will be removed in the next major version of typescript-eslint.

如果将其设置为 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 基本上会从类型中删除 undefinednull。这意味着当此规则检查变量的类型时,它将无法判断变量可能是 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.

何时不使用它

¥When Not To Use It

如果你的项目不太可能遇到逻辑条件中使用的虚假非布尔值导致的错误,则可以跳过启用此规则。

¥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.

相关

¥Related To


Type checked lint rules are more powerful than traditional lint rules, but also require configuring type checked linting.

See Troubleshooting > Linting with Type Information > Performance if you experience performance degradations after enabling type checked rules.

'## 资源'