Skip to content
← Back to rules

unicorn/prefer-default-parameters Style

🛠️ An auto-fix is available for this rule.

它的作用

应使用默认参数,而不是重新赋值函数参数。当 foo 为假值时,foo = foo || 123 语句会求值为 123,这可能导致令人困惑的行为;而默认参数只会在传入 undefined 值时生效。 此规则只会报告对字面量值的重新赋值。

如果你希望函数以处理 null 和其他假值的方式与 undefined 相同,请禁用此规则。 默认参数仅在 接收到 undefined 应用。 不过,我们建议 逐步摆脱 null

为什么这很糟糕?

使用默认参数可以清楚地表明某个参数具有默认值,从而提升代码的可读性和可维护性。

示例

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

js
function abc(foo) {
  foo = foo || "bar";
}

function abc(foo) {
  const bar = foo || "bar";
}

以下是此规则的正确代码示例:

js
function abc(foo = "bar") {}

function abc(bar = "bar") {}

function abc(foo) {
  foo = foo || bar();
}

如何使用

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

json
{
  "rules": {
    "unicorn/prefer-default-parameters": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  rules: {
    "unicorn/prefer-default-parameters": "error",
  },
});
bash
oxlint --deny unicorn/prefer-default-parameters

版本

此规则是在 v1.33.0 中添加的。

参考资料