Movatterモバイル変換


[0]ホーム

URL:


TypeScript Deep Dive
Ctrlk
Powered by GitBook
On this page

Spread Operator

The main objective of the spread operator is tospread the elements of an array or object. This is best explained with examples.

Apply

A common use case is to spread an array into the function arguments. Previously you would need to useFunction.prototype.apply:

functionfoo(x, y, z) { }var args= [0,1,2];foo.apply(null, args);

Now you can do this simply by prefixing the arguments with... as shown below:

functionfoo(x, y, z) { }var args= [0,1,2];foo(...args);

Here we arespreading theargs array into positionalarguments.

Destructuring

We've already seen one usage of this indestructuring:

var [x, y,...remaining]= [1,2,3,4];console.log(x, y, remaining);// 1,2,[3,4]

The motivation here is to simply make it easy for you to capture the remaining elements of an array when destructuring.

Array Assignment

The spread operator allows you to easily place anexpanded version of an array into another array. This is demonstrated in the example below:

You can put the expanded array in at any position, and get the effect you'd expect:

Object spread

You can also spread an object into another object. A common use case is to simply add a property to an object without mutating the original:

For objects, the order of where you put the spread matters. This works something likeObject.assign, and does what you'd expect: what comes first is 'overridden' by what comes later:

Another common use case is a simple shallow extend:

Summary

apply is something that you often use in JavaScript, so it's good to have a better syntax where you don't have that uglynull for thethis argument. Also having a dedicated syntax for moving arrays out of (destructuring) or into (assignment) other arrays provides a neat syntax for when you are doing array processing on partial arrays.

Last updated


[8]ページ先頭

©2009-2025 Movatter.jp