Object Spread and Rest
TypeScript 2.1 brings support for ES2017 Spread and Rest.
Similar to array spread, spreading an object can be handy to get a shallow copy:
let copy = { ...original };
Similarly, you can merge several different objects.In the following example, merged
will have properties from foo
, bar
, and baz
.
let merged = { ...foo, ...bar, ...baz };
You can also override existing properties and add new ones:
let obj = { x: 1, y: "string" };
var newObj = {...obj, z: 3, y: 4}; // { x: number, y: number, z: number }
The order of specifying spread operations determines what properties end up in the resulting object;properties in later spreads “win out” over previously created properties.
Object rests are the dual of object spreads, in that they can extract any extra properties that don’t get picked up when destructuring an element:
let obj = { x: 1, y: 1, z: 1 };
let { z, ...obj1 } = obj;
obj1; // {x: number, y: number};