Skip to content

Prefer Optional Parameter

ErrorAuto-fixable
small-rules/prefer-optional-parameter

Disallow `undefined` in a function parameter's type union; declare the parameter optional with `?` instead.

Rationale

scenario?: ScenarioId and scenario: ScenarioId | undefined accept the same values. The first one lets the caller omit the argument. The second one still requires an argument, so the callee must handle undefined. The caller cannot tell whether the parameter is optional or whether undefined is a real value.

A default value and a rest parameter are already optional. The rule leaves them alone. It also leaves a parameter alone where ? is invalid. An optional parameter cannot come before a required one. An accessor setter cannot be optional. A destructuring parameter can only be optional in a declaration signature, not in a function with a body. In those positions the union is the only valid way to accept undefined, so the rule doesn’t report.

Diagnostic Messages

preferOptionalParameter
Parameter `{{parameter}}` includes `undefined` in its type. Declare it optional with `?` instead.

Configuration

This rule does not accept options.

{
"jsPlugins": [
"@pobammer-ts/small-rules"
],
"rules": {
"small-rules/prefer-optional-parameter": "error"
}
}

Examples

Undefined in a parameter union
function getOpeningTurns(scenario: ScenarioId | undefined): ReadonlyArray<ShownTurn> {}

After auto-fix

function getOpeningTurns(scenario?: ScenarioId): ReadonlyArray<ShownTurn> {}
Optional parameter syntax
function getOpeningTurns(scenario?: ScenarioId): ReadonlyArray<ShownTurn> {}