Aller au contenu principal

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

Spread syntax - MDN


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