In TypeScript, optional and default parameters are features that enhance the flexibility and usability of functions by allowing you to define
parameters that can be omitted during function calls or have default values assigned to them when not provided explicitly:
- Optional parameters are denoted by adding a question mark (
?
) after the parameter name in the function declaration. These
parameters can be omitted when calling the function, and TypeScript will assign them a value of undefined if they are not provided.
- Default parameters are used to assign a default value to a parameter in case the caller does not provide a value for that parameter. Default
values are specified in the function declaration using the assignment operator (
=
) followed by the default value.
When a parameter is defined as optional, it automatically allows that parameter to be omitted during function calls. If you explicitly pass
undefined
as the value for an optional parameter, it contradicts the purpose of making the parameter optional, making the code less
readable and maintainable.
Similarly, when a parameter has a default value, it means that if the caller omits the argument during function calls, the default value will be
used automatically. There is no need to pass undefined
explicitly for default parameters, except when they come before a required
parameter.
This rule checks that the last argument of a function call is not redundant with regard to the function’s signature.
function foo(x: number, y: string = "default", z?: number) {
// ...
}
foo(42, undefined); // Noncompliant: 'undefined' is redundant
foo(42, undefined, undefined); // Noncompliant: Both 'undefined' are redundant
foo(42, undefined, 5); // Compliant: 'undefined' is required to get the second parameter's default value
Instead of explicitly passing undefined
, simply omit the optional argument when calling the function to let TypeScript handle the
default value correctly.
function foo(x: number, y: string = "default", z?: number) {
// ...
}
foo(42);