functionApplySpreads
Prefer the spread operator over
.apply()calls.
✅ This rule is included in the tsstylisticandstylisticStrictpresets.
Before ES2015, one had to use Function.prototype.apply() to call variadic functions with an array of arguments.
In ES2015 and later, the spread operator (...) provides cleaner syntax for the same purpose.
This rule flags usage of .apply() when it can be replaced with spread syntax.
It only reports cases where the this argument is not changed, meaning the spread replacement is safe.
Examples
Section titled “Examples”const foo: any
foo.any
apply(var undefined
undefined, const args: any
args);const foo: any
foo.any
apply(null, const args: any
args);const obj: any
obj.any
foo.any
apply(const obj: any
obj, const args: any
args);var Math: Math
An intrinsic object that provides basic mathematics functionality and constants.
Math.Math.max(...values: number[]): number
Returns the larger of a set of supplied numeric expressions.
max.CallableFunction.apply<Math, number[], number>(this: (this: Math, ...args: number[]) => number, thisArg: Math, args: number[]): number (+1 overload)
Calls the function with the specified object as the this value and the elements of specified array as the arguments.
apply(var Math: Math
An intrinsic object that provides basic mathematics functionality and constants.
Math, const numbers: any
numbers);const foo: any
foo(...const args: any
args);const obj: any
obj.any
foo(...const args: any
args);var Math: Math
An intrinsic object that provides basic mathematics functionality and constants.
Math.Math.max(...values: number[]): number
Returns the larger of a set of supplied numeric expressions.
max(...const numbers: any
numbers);const foo: any
foo.any
apply(const otherThis: any
otherThis, const args: any
args);const foo: any
foo.any
apply(null, [1, 2, 3]);Options
Section titled “Options”This rule is not configurable.
When Not To Use It
Section titled “When Not To Use It”This rule should not be used if you need to target ES5 or earlier JavaScript environments that don’t support the spread operator.
If you have code that intentionally uses .apply() for readability or other reasons, you may want to disable this rule.
Further Reading
Section titled “Further Reading”Equivalents in Other Linters
Section titled “Equivalents in Other Linters”- ESLint:
prefer-spread - Oxlint:
eslint/prefer-spread