complete/require-variadic-function-argument
💼 This rule is enabled in the ✅ recommended config.
📝 Requires that variadic functions must be supplied with at least one argument.
💭 This rule requires type information.
Rule Details
Section titled “Rule Details”Variadic functions are functions that take a variable amount of arguments. However, as far as the TypeScript compiler is concerned, passing no arguments at all to a variadic function is legal. But doing this is usually a bug. For example:
const myArray = [1, 2, 3];myArray.push(); // Oops!Here, the author of the code made a typo and forgot to supply the thing to be
inserted into the array. Thus, the myArray.push line is a no-op.
To protect against these kinds of errors, this rule requires that you always pass at least one argument to a variadic function.
The rule checks a function only when its rest parameter is its only parameter
(not counting a this parameter) and the rest parameter has an array type.
Thus, it does not report:
- A rest parameter that follows other parameters, such as in
setTimeoutorarray.splice. These arguments are optional extras. - A rest parameter with a tuple type or a type parameter, such as in
Function.prototype.calloriterator.next. TypeScript already checks the number of arguments for these. - A rest parameter of type
any[]orunknown[], such as in a mock function. It accepts any arguments, including none.
Hard-Coded Exceptions
Section titled “Hard-Coded Exceptions”This rule is hard-coded to not throw an error with console methods (such as
console.log or console.error), since:
- It is relatively common to use these functions with no arguments in order to print a newline.
- The TypeScript signatures for those functions are weird in that they have a rest parameter as the second parameter instead of the first one.
It also allows element.replaceChildren() with no arguments, which is the usual
way to remove every child of a DOM element.
JSDoc Exceptions
Section titled “JSDoc Exceptions”Sometimes, a variadic function can be written to intentionally allow for zero
arguments. If this is the case, you can use a @allowEmptyVariadic JSDoc tag
inside of the JSDoc comment for the function. Then, this rule will ignore any
calls of that function.
For example, something like the following:
/** * Helper function to get all of the cars in the database. By default, it will return every car. * * You can optionally specify one or more car types to return only the cars that match the specified * car types. * * @allowEmptyVariadic */function getCars(...carTypes: CarType[]) {}Options
Section titled “Options”This rule is not configurable.
