Skip to main content

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