Classes, Spread operator, Arrow functions and Immutability in TypeScript

This post is showing you some tips to work with TypeScript, also help you a little bit getting familiar with TypeScript.

In order to explore Classes, Spread operator, Arrow functions and Immutability we will go through a simple application written by Javascript then converting to Typescript. Let’s say we are creating a ToDo list app with its typical functions such as Add or Remove item in the list.

Create a function called ToDoList and create an instance of it:

function ToDoList() {
this.list = [];
}
var myList = new ToDoList();

Next, we create a function to add an item to the list:

ToDoList.prototype.addItem = function (item) {
this.list.push(item);
}

And also remove an item of this list:

ToDoList.prototype.removeItem = function (item) {
var index = this.list.indexOf(item);
if(index > -1) {
this.list.splice(index, 1);
}
}

Then prints it out:


ToDoList.prototype.print = function () {
console.log(this.list);
}

Well, we have finished the ToDoList app with Javascript, now let’s see how we use Classes, Spread operator, Arrow function and Immutability in TypeScript.

Classes

With function ToDoList above, we are re-writing it with a Typescript class.

class ToDoList {
list: Array<string>;
constructor() {
this.list = [];
}
}
var myList = new ToDoList();

As you can see it’s very clear that we know type of list is array of strings.

Immutability

In our case, the addItem and removeItem functions we can re-write like this:

addItem(item: string) {
this.list = this.list.concat([item]);
}
removeItem(item: string) {
this.list = this.list.filter(function(i) {
return i !== item;
});
}

In Angular 2 (4), there are some cases you may need to write immutability functions. Here is a very good blog post that will help you understand why immutability is important.

Arrow functions

Typescript also supports Arrow function, it helps us write simply code and is able to keep this context inside a callback function as well.


removeItem(item: string) {
this.list = this.list.filter(i => i !== item);
}

As you can see, we even don’t need return statement, it’s implicitly way of return.

Spread operator

It’s also a interesting thing of Typescript you should know. We’ve added a new item in the list by using concat, there is another simpler way.

addItem(item: string) {
this.list = […this.list, item];
}

Is it cool? ;)

Conclusion

OK, it’s time to push all together, of course in TypeScript.

class ToDoList {
list: Array<string>;
constructor() {
this.list = [];
}
 addItem(item: string) {
this.list = […this.list, item];
}
 removeItem(item: string) {
this.list = this.list.filter(i => i !== item);
}
 print() {
console.log(this.list);
}
}

Hope you enjoy these interesting things of TypeScript.

Checkout more TypeScript posts.