Typescript Object Destructuring Tutorial with Angular

Typescript supports this idea of breaking up the structure of an object. What would normally take a few lines of code to write, you can do in a single line. There are two basic forms of destructuring: Object and Arrary. This article will focus on object destructoring.

We start out with an interface:

export interface Person {
age: number;

Normally, we would just pass the entire object to a function to manipulate some data.

incrementAge( person: Person){
person.age = person.age + 1;

Now imagine your Person class was “very big and complex”, and you just wanted to modify one property of the object.

export interface Person {
name: string;
street: string;
car: boolean;
age: number;

We want to make a new function to increment the persons age. Here we only care about two of the properties.

happyBirthday( {age, car} ){


I am going to make a simple form for our interface.

<form #f="ngForm" (ngSubmit)="onSubmit(f)" novalidate>
<label for="name">Name</label>
<input name="name" ngModel required #first="ngModel">
<label for="age">Age</label>
<input name="age" ngModel>
<label for="street">Street</label>
<input name="street" ngModel>
<label for="car">Car</label>
<input name="car" ngModel>
<p>Form value: {{ f.value | json }}</p>
<p>After submitting: {{item | json}}</p>

When the Submit button is clicked, I want to call a function to increment the age of the person without passing the entire object.

onSubmit(f: NgForm) {
//note you can see the entire object
happyBirthday( { age, car } ){
console.log(age + '' + car);
this.item.age = Number(age) + 1;
this.item.car = "red";

After Submitting:

Here is the git repo.

To run in development mode, open a terminal and run:

ng serve — open

To build for production with AOT and treeshaking:

ng build --prod --build-optimizer

Download Chrome Extension or visit https://moon.ly