Skip to content
← Back to rules

typescript/no-unnecessary-condition Nursery

💭 This rule requires type information.

它的作用

禁止始终为真、始终为假或始终为 nullish 的条件, 基于 TypeScript 的类型信息。

为什么这很糟糕?

没有任何运行时变化可能性的条件会让代码更难阅读,并且可能 隐藏逻辑错误。它们通常会留下死分支,并暗示声明的 类型与预期行为不匹配。

示例

以下是此规则的错误代码示例:

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"

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

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

checkTypePredicates

type: boolean

default: false

是否检查类型谓词函数。

如何使用

To enable this rule using the config file or in the CLI, you can use:

json
{
  "options": {
    "typeAware": true
  },
  "rules": {
    "typescript/no-unnecessary-condition": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  options: { typeAware: true },
  rules: {
    "typescript/no-unnecessary-condition": "error",
  },
});
bash
oxlint --type-aware --deny typescript/no-unnecessary-condition

版本

此规则在 v1.48.0 中添加。

参考资料