Skip to content

noUnnecessaryConditions

¥Summary

¥How to configure

biome.json
{
"linter": {
"rules": {
"nursery": {
"noUnnecessaryConditions": "error"
}
}
}
}

¥Description

禁止使用静态方法判断为冗余的、不必要的基于类型的条件。

¥Disallow unnecessary type-based conditions that can be statically determined as redundant.

此规则检测条件语句中的表达式是否可静态推断,以及它们产生的真值或假值在程序生命周期内是否保持不变。

¥This rule detects if expressions inside conditions are statically inferrable and yield falsy or truthy values that don’t change during the life cycle of the program.

¥Examples

¥Invalid

function head<T>(items: T[]) {
if (items) { // This check is unnecessary
return items[0].toUpperCase();
}
}
function foo(arg: 'bar' | 'baz') {
if (arg) { // This check is unnecessary
}
}
function bar(arg: string) {
return arg?.length; // ?. is unnecessary
}

与源规则不同,此规则不会触发分配给多个值的绑定。在以下示例中,变量 greeting 被赋予多个值;因此,它无法推断为真值或假值。

¥Contrary to the source rule, this rule doesn’t trigger bindings that are assigned to multiple values. In the following example, the variable greeting is assigned to multiple values; hence it can’t be inferred to a truthy or falsy value.

let greeting = false;
function changeGreeting() {
greeting = "Hello World!"
}
if (greeting) {} // rule not triggered here

¥Valid

function head<T>(items: T[] | null) {
if (items) { // This check is necessary
return items[0].toUpperCase();
}
}
function foo(arg: 'bar' | 'baz' | null) {
if (arg) { // This check is necessary
}
}
function bar(arg: string | undefined) {
return arg?.length; // ?. is necessary
}

¥Related links