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];