TypeScript Object Rest

In my last post,  I focused on TypeScript Object Spread. Today I want to highlight a feature of TypeScript that uses a similar syntax, TypeScript Object Rest:


// Here we use object rest to pass a variable number of parameters
function test(a, ...args){
// args is an array of params
if (args.length){
// ....
}
}

As shown in the above example, object rest is a way to pass a variable number of parameters to a function.

Another way to use it is to apply it to objects:


// We create a simple object
let obj = { x: 1, y: 2, z: 3};
let {z, ...obj1} = obj;
// obj1 is now { x: 1, y: 2 }

The above example is a little bit tricky. What it does is initialize a new variable obj1, which is all of obj but z.

In other words, obj1 is the rest of obj minus z. As a result, obj1 only has the x and y properties.

Now we can apply the same syntax to arrays:


// We create a simple array
let arr = [1, 2, 3, 4];
let [first, second, ...arr1] = arr;
// arr1 = [3, 4], first = 1 and second = 2

The above is also called array destructuring.

Now you know everything there is to know about TypeScript Object Rest. It’s a very useful and powerful syntax that brings both clarity and simplicity to your code when needed.

Alain Chautard

Alain started working with Angular JS in 2011, back when version 1.0 wasn’t even released yet.

He is the organizer of the Sacramento Angular Meetup group, co-organizer of the Google Developer Group chapter in Sacramento, California, and published author of the Packt video course “Migrating to Angular 2“.