spread()
spread<
Result>(func,start): (args) =>Result
Creates a function that invokes func with the this binding of the create function and an array of arguments much like Function#apply.
๐ Why is this a Hidden Gem?
Convert a function that takes an array into one that takes individual arguments.
DEPRECATED
Use the spread operator ... directly instead.
Type Parametersโ
Result: Resultโ
The return type of the function.
Parametersโ
func: (...args) => Resultโ
The function to spread arguments over.
start: number = 0โ
The start position of the spread. Defaults to 0.
Returnsโ
The new function.
See Alsoโ
Sinceโ
2.0.0
Also known asโ
spread (Lodash, es-toolkit) ยท โ (Remeda, Radashi, Ramda, Effect, Modern Dash, Antfu)
Exampleโ
// โ Deprecated approach
const say = spread((who: string, what: string) => who + ' says ' + what);
say(['fred', 'hello']);
// => 'fred says hello'
// โ
Recommended approach
const say = (who: string, what: string) => who + ' says ' + what;
const args: [string, string] = ['fred', 'hello'];
say(...args);
// => 'fred says hello'
How it works?โ
Creates a function that spreads array as arguments. Deprecated: Use spread syntax directly.
Native Equivalentโ
// โ spread(fn)(args)
// โ
fn(...args)
Use Casesโ
Spread array as arguments ๐โ
Apply array elements as function arguments.
const add = (a, b, c) => a + b + c;
const nums = [1, 2, 3];
add(...nums); // => 6
Call with arrayโ
Use array as function parameters.
Math.max(...[1, 5, 3, 9, 2]);
// => 9
Merge arraysโ
Combine arrays using spread.
const all = [...arr1, ...arr2, ...arr3];