Aller au contenu principal

rest()

rest<Result>(func, start?): (...args) => Result

Creates a function that invokes func with the this binding of the created function and an array of arguments.

DEPRECATED

Use rest parameters (...args) syntax directly instead.


Type Parameters

Result: Result

The return type of the function.


Parameters

func: (...args) => Result

The function to apply a rest parameter to.

start?: number

The start position of the rest parameter. Defaults to func.length - 1.


Returns

The new function.


See Also

Rest parameters - MDN


Since

2.0.0


Also known as

rest (Lodash, es-toolkit) · ❌ (Remeda, Radashi, Ramda, Effect, Modern Dash, Antfu)


Example

// ❌ Deprecated approach
const say = rest((what: string, names: string[]) => {
return what + ' ' + names.join(', ');
});
say('hello', 'fred', 'barney', 'pebbles');
// => 'hello fred, barney, pebbles'

// ✅ Recommended approach
const say = (what: string, ...names: string[]) => {
return what + ' ' + names.join(', ');
};
say('hello', 'fred', 'barney', 'pebbles');
// => 'hello fred, barney, pebbles'

How it works?

Creates a function that collects arguments into array. Deprecated: Use rest parameters directly.

Native Equivalent

// ❌ rest(fn)
// ✅ (...args) => fn(args)

Use Cases

Collect remaining arguments 📌

Collect remaining arguments into array.

const log = (first, ...rest) => {
console.log(first, rest);
};
log(1, 2, 3, 4); // => 1, [2, 3, 4]

Forward arguments

Pass through all but first arguments.

const wrapper = (fn, ...args) => fn(...args);

Variadic functions

Accept any number of arguments.

const sum = (...nums) => nums.reduce((a, b) => a + b, 0);
sum(1, 2, 3, 4); // => 10