Skip to main content

no-unnecessary-condition

Disallow conditionals where the type is always truthy or always falsy.

🔒

ESLint 配置 中扩展"plugin:@typescript-eslint/strict-type-checked" 可启用此规则。

🔧

此规则报告的一些问题可通过 --fix ESLint 命令行选项自动修复

💭

该规则需要 类型信息 才能运行。


任何用作条件的表达式都必须能够计算为真或假,才能被视为 "necessary"。 相反,任何始终计算结果为真或总是计算结果为假的表达式(由表达式的类型决定)都被认为是不必要的,并将被此规则标记。

英:Any expression being used as a condition must be able to evaluate as truthy or falsy in order to be considered "necessary". Conversely, any expression that always evaluates to truthy or always evaluates to falsy, as determined by the type of the expression, is considered unnecessary and will be flagged by this rule.

检查以下表达式:

英:The following expressions are checked:

  • &&||?:(三元)运算符的参数
  • ifforwhiledo-while 语句的条件
  • 可选链表达式的基值
.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/no-unnecessary-condition": "error"
}
};
在线运行试试这个规则 ↗

示例

function head<T>(items: T[]) {
// items can never be nullable, so this is unnecessary
if (items) {
return items[0].toUpperCase();
}
}

function foo(arg: 'bar' | 'baz') {
// arg is never nullable or empty string, so this is unnecessary
if (arg) {
}
}

function bar<T>(arg: string) {
// arg can never be nullish, so ?. is unnecessary
return arg?.length;
}

// Checks array predicate return types, where possible
[
[1, 2],
[3, 4],
].filter(t => t); // number[] is always truthy
Open in Playground

选项

allowConstantLoopConditions

{ allowConstantLoopConditions: true } 的正确代码示例:

英:Example of correct code for { allowConstantLoopConditions: true }:

while (true) {}
for (; true; ) {}
do {} while (true);
Open in Playground

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 本质上会从类型中删除 undefinednull。 这意味着当该规则检查变量 它无法判断该变量可能是 nullundefined 的类型时,这实际上使该规则毫无用处。

英: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 useless.

你应该使用 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.

何时不使用它

如果你的项目类型不准确,例如正在转换为 TypeScript 或容易受到 控制流分析中的权衡 的影响,则对于特别是非类型安全的代码区域可能很难启用此规则。 你可以考虑在这些特定情况下使用 ESLint 禁用注释,而不是完全禁用此规则。

英:If your project is not accurately typed, such as if it's in the process of being converted to TypeScript or is susceptible to trade-offs in control flow analysis, it may be difficult to enable this rule for particularly non-type-safe areas of code. You might consider using ESLint disable comments for those specific situations instead of completely disabling this rule.

该规则有一个已知的边缘情况,即在函数调用内修改的条件下触发(作为副作用)。 这是由于 TypeScript 类型缩小的限制。 详情请参见 #9998。 在这些情况下,我们建议使用 类型断言

英:This rule has a known edge case of triggering on conditions that were modified within function calls (as side effects). It is due to limitations of TypeScript's type narrowing. See #9998 for details. We recommend using a type assertion in those cases.

let condition = false as boolean;

const f = () => (condition = true);
f();

if (condition) {
}
  • ESLint: no-constant-condition - no-unnecessary-condition 本质上是 no-constant-condition 的更强版本,但需要类型信息。
  • strict-boolean-expressions - no-unnecessary-condition 的更有态度的版本。 strict-boolean-expressions 强制执行特定的代码风格,而 no-unnecessary-condition 则与正确性有关。

选项

该规则接受以下选项

type Options = [
{
/** Whether to ignore constant loop conditions, such as `while (true)`. */
allowConstantLoopConditions?: boolean;
/** Whether to not error when running with a tsconfig that has strictNullChecks turned. */
allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing?: boolean;
},
];

const defaultOptions: Options = [
{
allowConstantLoopConditions: false,
allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing: false,
},
];

资源