Skip to content
← Back to rules

typescript/no-unnecessary-condition Nursery

💭 This rule requires type information.

它的作用

根据 TypeScript 的类型信息,禁止总是真、总是假或总是空值(nullish)的条件表达式。

为什么这是不好的?

没有可能的运行时变化的条件会使代码更难阅读,并可能隐藏逻辑错误。它们通常会导致死代码分支,暗示声明的类型与预期行为不符。

示例

此规则的 错误 代码示例:

ts
declare const value: null;
if (value) {
  doWork();
}

const items: string[] = [];
if (items) {
  doWork();
}

declare const status: "ready";
if (!status) {
  reportError();
}

此规则的 正确 代码示例:

ts
declare const maybeUser: User | undefined;
if (maybeUser) {
  doWork(maybeUser);
}

const items: string[] = [];
if (items.length > 0) {
  doWork();
}

declare const status: "ready" | "";
if (!status) {
  reportError();
}

配置

此规则接受一个配置对象,包含以下属性:

allowConstantLoopConditions

type: boolean | "never" | "always" | "only-allowed-literals"

表示 allowConstantLoopConditions 在 JSON 中可以指定的不同方式。可选值为:

  • truefalse
  • 字符串枚举("never""always""only-allowed-literals"

checkTypePredicates

type: boolean

default: false

是否检查类型谓词函数。

如何使用

要通过配置文件或 CLI 启用 此规则,可以使用:

json
{
  "rules": {
    "typescript/no-unnecessary-condition": "error"
  }
}
bash
oxlint --type-aware --deny typescript/no-unnecessary-condition

参考资料